Python-Tutorial

Today Python is taught and learned at school, so maybe it became somthing scholar, and maybe it is not something as enjoyable anymore as if it was there only for the hobbies, but I will try to make a presentation as attractive as I can. I want to appology if this goal is not fully reached.
I read that the implementation is written in C++, but I didn't checked if it's true or not. The online playground is probably written in javascript.
If I'm not mistaken, this is a language that comes from england, but there are probably contribution from all arround the globe.


A simple function

Here is how to write a simple function:
$ python3
Python 3.11.2
>>> def add(a, b):
...   return a + b
...
>>> add(2, 3)
5

The range() structure

The range() structure is an equivalent for the for loops of the master language (.c):
$ python3
Python 3.11.2
>>> for x in range(2, 5):
...     print(f"x = {x}")
...
x = 2
x = 3
x = 4
Be carefull, the last number is not included, as you can see in the example.

Text

Unfortunatly this is not that easy to make text manipulations in python, everytime you want to change one char, you have to create a new text variable:
$ python3
Python 3.11.2
>>> s = 'hello'
>>> s = 'H' + s[1:]
>>> s
'Hello'
>>> s + '!'
'Hello!'
To make real text manipulations, maybe one solution would be to use arrays and slices.

Arrays

Arrays in python are dynamic, unlike text it is easy to modify an array, and to add elements at the end or at the beginning.
$ python3
Python 3.11.2
>>> num = [29, 149, 399]
>>> num
[29, 149, 399]

>>> num.append(479)
>>> num
[29, 149, 399, 479]
>>>

Index, len() and Slices

The index of an array starts at 0 (zero).
The len() function is the standard function to get the number of elements in an array.
We can slice an array with the character [:] inside the square brackets, with eventualy an index before and after, as in [2:5]. Here there are only 4 elements, so we will use small indices.
$ python3
Python 3.11.2
>>> num
[29, 149, 399, 479]
>>> num[0]
29
>>> len(num)
4
>>> num[2:]
[399, 479]
No indices before the [:3] char means to slice from the beginning, and no indices at the end [2:] means to slice from the given index, until the end.
The element at index [3] is 479, when we slice an array, the end index is excluded:
>>> num
[29, 149, 399, 479]

>>> num[3]
479

>>> num[:3]
[29, 149, 399]
Because the first index is 0, if there are 4 elements the last one will be index 3.
>>> num
[29, 149, 399, 479]

>>> num[0]
29
>>> num[1]
149
>>> num[2]
399
>>> num[3]
479
>>> num[4]
IndexError

P6 image

Here is a small script to create a P6 image:
w = 240 # width
h = 180 # height
img = []

for y in range(0, h):
  line = []
  for x in range(0, w):
    line.append([0, 0, 0]) # rgb
  img.append(line)

print(f"P6")
print(f"{w} {h}")
print(f"255")

for y in range(0, len(img)):
  for x in range(0, len(img[y])):
    c0 = img[y][x][0]
    c1 = img[y][x][1]
    c2 = img[y][x][2]
    print(chr(c0), end="")
    print(chr(c1), end="")
    print(chr(c2), end="")

Put this small script in a text file called img.py, then it is possible to call this script with the python command.
$ python3 img.py > img.ppm
The output of the script will be redirected to the file img.ppm with the char: >
Then the result image can be visualized with an image visualizer like feh:
$ feh img.ppm
With the following line, we initialize an empty array,
  line = []
Then every pixel of the line will be added with:
    line.append()
then when the line is finished, it is added to the img variable in the same way:
    img.append(line)
the img variable was also initialised in the same way as an empty array, where we add every line of the image.
    [0, 0, 0] # rgb
This three element array, contains the three primary colors:
Red, Green, Blue
We can create every color, mixing these three primary colors.
  range(0, len(var))
We can use the len() function inside the range() structure, because the last index will be the previous number.
The x for loop is the inside loop because it is easier and more natural to iterate by line.

Structuring Code

The previous code will be better organised with functions.
It is better to proceed by steps though, starting with the easier and simpler structure.
So we create three functions create_img(), print_img(), and main().
main will be the entry point, as in the master language, and will be called at the end:

def create_img(w, h):
  img = []
  for y in range(0, h):
    line = []
    for x in range(0, w):
      line.append([0, 0, 0])
    img.append(line)
  return img

def print_img(img):
  w = len(img[0])
  h = len(img)
  print(f"P6")
  print(f"{w} {h}")
  print(f"255")
  for y in range(0, len(img)):
    for x in range(0, len(img[y])):
      c0 = img[y][x][0]
      c1 = img[y][x][1]
      c2 = img[y][x][2]
      print(chr(c0), end="")
      print(chr(c1), end="")
      print(chr(c2), end="")

def main():
  w = 240 # width
  h = 180 # height
  img = create_img(w, h)
  print_img(img)

main()

If you want to compare several versions, you can put several main's near each other's, as in:
main1(), main2(), main3().

Evolution

Then we can add a draw_rect() function to draw a rectangle.

def draw_rect(img, _x, _y, _w, _h, color):
  for y in range(_y, _y + _h):
    for x in range(_x, _x + _w):
      img[y][x][0] = color[0]
      img[y][x][1] = color[1]
      img[y][x][2] = color[2]

After we can add some bound check,

def draw_rect(img, _x, _y, _w, _h, color):
  w = len(img[0])
  h = len(img)
  for y in range(_y, _y + _h):
    for x in range(_x, _x + _w):
      if x >= 0 and x < w:
        if y >= 0 and y < h:
          img[y][x][0] = color[0]
          img[y][x][1] = color[1]
          img[y][x][2] = color[2]

I don't get the expected result with this function.
Here is what I get:
python-image
When I write it with another scripting language, here is what I get:
image-with-another-scripting-language
I tryed to check every line, line by line, but i'm not able to figure-out where could be the problem.
In the following bound check:
      if x >= 0 and x < w:
The comparision with 0 is >= because the first index is 0, and the comparision with w is <, because if there are 10 elements in an array, the last index will be 9.

  img = create_img(w, h)
  draw_rect(img, 10, 10, 80, 30, [255, 0, 0])
  print_img(img)

Install

$ sudo apt-get install python3
The name of a package is different in every distribution, so probably you will have to find it by yourself.

PyGame

$ sudo apt-get install python3-pygame
The name of pygame is also probably different in every distribution, so you will probably also be alone with no help to find it.

Text Manipulation's

$ python3
Python 3.11.2
>>> s = "hello"
>>> chars = []
>>> n = len(s)
>>> for d in range(0, n):
...   chars.append(s[d])
... 
>>> chars
['h', 'e', 'l', 'l', 'o']
As you can see, now you can make real text manipulation's:
>>> chars[0] = 'H'
>>> chars
['H', 'e', 'l', 'l', 'o']
How to convert it back to pure text:
>>> n = len(chars)
>>> n
5
>>> txt = ''
>>> d = 0
>>> while d < n:
...   txt += chars[d]
...   d += 1
...
>>> txt
'Hello'
Slices on text or arrays seem to be made in the same way.

Going Further

If you like games or demo's, you can make one with pygame.
If you like to create images, as you can see I will not be able to tell you how you can do, as you probably noticed with my p6 example.
If your parents like murder-parties, you can probably create one in a pure textual way with this language.
Or you can create some currency-lib with some cryptic algorythm.

Usage Notice

© 2025 Florent Monnier
License for the tutorial parts:
license: FDL
License for the code parts:
To the extent permitted by law:
spdx=any

back to the table of contents
The Python Language