Module 1: Python basics · 11 min
Decisions and loops
if, elif and else let a program choose. Indentation (4 spaces) shows which lines belong inside.
marks = 68
if marks >= 80:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print(grade) # B
A for loop repeats code for each item. range(5) gives 0, 1, 2, 3, 4.
for i in range(3):
print("Round", i)
total = 0
n = 1
while n <= 5:
total += n
n += 1
print(total) # 15
- Comparison: == (equal), != (not equal), <, >, <=, >=.
- Combine conditions with and, or, not.
- Use while only when you do not know how many times to repeat. Make sure the condition can become false, or the loop never ends.