HomeTurtlegraficsGPanelRobotics WebTigerPython
 Python - Online
crahCourse
Deutsch   English   

PYTHON CRASH COURSE

 

 

YOU LEARN HERE...

 

the most important things about programming with Python using simple examples with a glowbug, which you can move on the micro:bit display using the forward(), left(), right() and back() commands. If you have already familiarised yourself with Python in the Turtlegraphics chapter or have an equivalent basic knowledge of Python, you can skip this chapter and go straight to the next menu item.

 

 

PROGRAM STRUCTURE SEQUENCE

 

A computer program consists of a sequence of programme lines that are executed one after the other (as a sequence). So that you can use the beetle commands, you must import the mbglow module with from mbglow import *.

Use the makeGlow()command to create a visible beetle in the centre of the display. It is just a single glowing LED. When the beetle moves, LEDs are switched on at the positions it visits, so it leaves a trail, so to speak.

Your commands are executed after downloading the programme to the micro:bit.

 

The commands are always written in English and always end with a parameter bracket. This can contain further information for the command. You must adhere exactly to upper/lower case.

With forward() the beetle moves one step forwards in the current direction of movement. When the programme starts, the direction of movement points upwards. With left(90) the beetle turns 90 degrees to the left and with right(90) 90° to the right. However, this only becomes noticeable with the next forward() command.

With your programme, the beetle draws the track shown next to it:

Program:

from mbglow import *

makeGlow()

forward()
left(90)
forward()
right(90)
forward()
►Copy to clipboard

 
By clicking on the ‘WebTigerPython’ button, the programme is introduced into WebTigerPython and can be executed immediately. If you already have WebTigerPython open, click on Copy to clipboard and paste the programme into the editor window with Ctrl+V

 

 

REPEAT

 

To run through a square, the beetle must execute the forward() and left(90) commands four times. You can save yourself a lot of typing by using a repeat loop. You simply write repeat 4: (the colon is important). The commands that are to be repeated must all be equally spaced. You can use four spaces or the tab key..

 

Program:

from mbglow import *

makeGlow()

repeat 4:
    forward()
    left(90)
►Copy to clipboard

 

You want to draw a square as large as possible. To do this, use setPos(-2, -2)to place the beetle in the bottom left corner. With setPos(x, y), the beetle is set to any new position. To make it visible, you must select -2, -1, 0, 1 or 2 for x and y.

To draw a square side, move the beetle forwards 4 times. You can also use a repeat loop for these 4 forward steps. Your programme therefore has two nested repeat loops.

 

Make sure the indentation is correct!

Program:

from mbglow import *

makeGlow()

setPos(-2, -2)
repeat 4:
    repeat 4:
        forward()
    right(90)
►Copy to clipboard

 

 

FUNCTIONS (NAMED PROGRAMME BLOCKS)

 

With named program blocks, called functions in Python, you can make your programmes clearer. You can also call functions several times. The use of functions is very important because you avoid having to write the same code several times in the programme (code duplication) and you can break problems down into smaller problems.

In your example, you define a function square() that moves the beetle on a square.

The function definition begins with the keyword def, followed by the function name, a parameter bracket and a colon. The commands in the function body must be indented. Note that the commands are only executed when the function is called The function definitions are always at the top of the programme.

 

For the function name, choose an identifier that says something about what the function does. You may not use any special characters (spaces, umlauts, accents, punctuation marks, etc.). Always start the name with a small letter. In the following programme, you define a function square() that draws a square and then execute it.

Program:

from mbglow import *

makeGlow()

def square():
    repeat 4:
        forward()
        forward()
        left(90)

square()
►Copy to clipboard


With the definition of square() you have introduced a new function, so to speak, which you can now use as often as you like. To create the adjacent image, call the square() function 4 times.

With the command setSpeed(80) the beetle runs faster. (The default value is 50 and values in the range 0 to 100 are permitted).

 

Program:

from mbglow import *

makeGlow()

def square():
    repeat 4:
        forward()
        forward()
        left(90)

setSpeed(80)
repeat 4:
    square()
    right(90)
►Copy to clipboard

 

 

VARIABLES

 

In computer science, variables are placeholders for values that change in the course of programme execution. A variable therefore has a name and a value.

v is the speed of the beetle. With v = 30 , you set v to the initial value 30. This command is called an assignment. This is increased by 20 after every square that is run through.

 

To do this, you use the command v = v + 20 , which at first glance looks like a nonsensical equation, but tells the computer to get the existing value of v and add 20 to it, and then store the result in v again. The command showTrace(False) causes the beetle to leave no trace.

Program:

from mbglow import *

makeGlow()

def square():
    repeat 4:
        forward()
        forward()
        right(90)
    
v = 30
showTrace(False)
setPos(-1, -1)

repeat 4:
    setSpeed(v)
    square()
    v = v + 20
►Copy to clipboard

 

 

WHILE LOOP

 

The while loop is one of the most important programme structures of all. It can generally be used for any type of repetition and is found in practically all programming languages. A while loop is introduced with the keyword while followed by a condition and a colon. As long as the condition is fulfilled, the commands in the following programme block are repeated. Colloquially, this would be expressed as follows:

As long as the condition is true, execute ...

The comparison operators < (smaller), <= (smaller-equal), > (greater) >= (greater-equal), == (equal), != (different) are usually used in the condition. Note the doubling of the equals sign when testing for equality (so that it is not confused with an assignment).

In your example, the beetle first moves 2 steps forwards, then 2 steps backwards, rotates by 45°, then 2 steps forwards again and so on until it is facing north again. You store the total angle of rotation in the variable a. You start with a = 0 and add 45 after each loop pass. As long as the condition a <= 360 is true, the indented instructions are executed.

 


Program:

from mbglow import *

makeGlow()

setSpeed(90)
showTrace(False)
a = 0
while a <= 360:
    forward()
    forward()
    back()
    back()
    left(45)    
    a = a + 45
►Copy to clipboard


In robotics, a so-called ‘endless while loop’ is often used. This is introduced witht while True: As True is always true, the loop is executed until you end the programme execution in the adjacent console window with Ctrl+C or interrupt the power supply to the micro:bit. clear() deletes all LEDs.

 

Program:

from mbglow  import *

makeGlow()

def square():
    repeat 4:
        forward()
        forward()
        left(90)

clear()
setSpeed(90)
showTrace(False)
setPos(2, 0)
left(45)
while True:
    square()
►Copy to clipboard

 

 

FOR IN RANGE LOOP

 


In a repeat loop, you often need an integer variable that increases by one with each pass. You can solve this with a while loop, but it is easier with a for loop, in which the loop counter is automatically changed.
for i in range(n) runs through numbers i from 0 to n-1
for i in range(a, b) runs through numbers i from a to b-1
Note that the final value n or b is never included.

 

With for x in range(-2, 3) , x runs through the values -2, -1, 0, 1, 2. The LEDs in the top row are switched on one after the other. With sleep(500) you can stop the programme execution for 500 milliseconds so that you can observe the process better.

Program:

from mbglow import *

makeGlow()

clear()
for x in range(-2, 3):
    setPos(x, 2)
    sleep(500)
►Copy to clipboard

 

 

IF - ELSE (SELECTION)

 

You can use the selection to ensure that certain programme blocks are only executed under certain conditions. The selection is introduced with the keyword if, followed by a condition. The statements in the if are only executed if the condition is true, otherwise the statements after else are executed. The comparison operators >, >= , < , <= , == , != are usually used in the if condition. The statements in the if or else block must be indented. The else part can also be omitted.

In this example, the beetle moves to the right. When it reaches the right edge, it jumps back to the left edge and repeats this movement from left to right endlessly. So you move the beetle to the right with forward() and check its x-coordinate after each step. If it is 3, the beetle is moved back to the left edge (x = -2).

 

Program:

from mbglow import *

makeGlow()

right(90)
x = 0
showTrace(False) 

while True:
    forward()
    x = x + 1  
    if x == 3:
        setPos(-2, 0)        
        x = -2 
►Copy to clipboard

In the next programme, the beetle should randomly move two steps forwards or two steps backwards, then stop briefly, delete the track and return to the starting position. It should repeat this movement 10 times.

You use random numbers. The randint(a, b) function from the random module randomly generates an integer between a and b.

Therefore, the function randint(0, 1) randomly returns a 0 or a 1. If the value is 1, the beetle moves 2 steps forwards, , elset (if the number is 0) it moves 2 steps backwards.

 

 

Program:

from mbglow import *
from random import randint

makeGlow()
setSpeed(80)
repeat 10:    
    r = randint(0, 1)
    if r == 1:
        forward()
        forward()
    else:
        back()
        back()     
    sleep(300)
    clear()
    setPos(0, 0) 
►Copy to clipboard

 

 

REMEMBER YOU...

 

The basic programme structures are sequence, repetition and selection. In a sequence, the commands are processed one after the other. With a repetition, programme blocks are executed several times. In TigerJython you can use the repeat; while or for loops for this purpose. The selection with if and else means that certain instructions are only executed under certain conditions. The else part can also be omitted.
Functions are important for structured programming. They avoid code duplication and serve to break problems down into smaller sub-problems. This is also referred to as modularisation.

 

 

TO SOLVE BY YOURSELF

 

 

1.
Write a programme with a repeat structure so that the firefly draws a plus sign.  

2a.
First place the beetle in the bottom left corner of the display using setPos(-2, -2). Then it should move up 4 steps.  

2b.

Solve the same task with a step() function that draws a single step and then call it 4 times with a repeat loop.

 

 

 

 

3.

Write a programme that switches on the LEDs in the two diagonals, i.e. draws a cross.

 

4.

As in the first example for if-else, the beetle moves from left to right. Here, however, it should not just run through one row, but all rows. The beetle therefore starts in the bottom left-hand corner and moves to the right. When it reaches the right edge, it jumps back to the left edge and continues its movement in the second row. Its y-coordinate therefore increases by 1

 

5.

To cycle through all the LEDs on the display, you can also use two for loops and switch on the LEDs with setPos(x, y):

for y in range(-2, 3):
    for x in range (-2, 3):
        setPos(x, y)

Your programme should run through all the LEDs, but only switch on the LEDs as shown in the adjacent figure.

 

6.

Your programme should switch on LEDs according to the adjacent ‘chessboard’ figure. As you can easily see, the illuminated LEDs fulfil the condition: the sum of their x and y coordinates is an even number. To check whether a number is even or odd, you usually use the modulo division a % b, which returns the remainder of the integer division of a by b. A number a is therefore even if a % 2 == 0.