Variables, Conditionals and Loops

30 min
0/3 practice checks

From blocks to typed code

In block coding you drag instructions. In text programming you type them. Python is one of the most popular text languages, and the rules are strict but simple.

A variable is a labelled box that holds a value. You put a value in with = (the assignment sign):

name = "Thandi"
age = 14
litres = 25.5

Here name holds text (a string), age holds a whole number (an int), and litres holds a decimal (a float). You can read a box, change it, or use it in a calculation.

python

Runs in your browser. Charts (matplotlib) are not supported — use print-based output.

Conditionals: making decisions

A program often has to choose. The if / elif / else structure lets it pick a path. Note the colon : and the indentation (4 spaces) that mark which lines belong inside each branch:

stage = 4
if stage == 0:
    print("No load-shedding")
elif stage <= 4:
    print("Moderate load-shedding")
else:
    print("Severe load-shedding")

Comparisons give a True/False answer: == (equal to), != (not equal), <, >, <=, >=.

Loops: repeating work

A loop repeats instructions so you do not copy-paste. A for loop repeats a set number of times; a while loop repeats as long as a condition stays True.

for day in range(1, 6):      # 1, 2, 3, 4, 5
    print("Study session", day)

charge = 20
while charge < 100:          # keep going until full
    charge = charge + 20

range(1, 6) counts 1 up to but not including 6.

python

Runs in your browser. Charts (matplotlib) are not supported — use print-based output.

A learner runs this code:

units = 50
units = units - 18
units = units + 5
print(units)

What number is printed?

A loop adds up the numbers from 1 to 10:

total = 0
for n in range(1, 11):
    total = total + n
print(total)

What value does it print? (Remember range(1, 11) gives 1, 2, 3, ... up to 10.)

In an if statement, which Python keyword lets you test a second condition only when the first if was False? (One word.)