Control flow: if, while, for
Conditions and loops, break and continue.
All lessons · Python lessons: learn from scratch
if / elif / else
if lets a program make decisions. When the condition is true the indented block runs. For several cases use elif, and else for everything left over; only the first true branch is executed.
score = 73
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"
print(grade) # BAn empty string, 0, an empty list and None count as “false” in a condition; other values count as “true”. This allows short checks such as if items:.
The while loop
while repeats its block as long as the condition is true. Something inside must change the condition, otherwise the loop never ends. break stops the loop at once and continue jumps to the next round.
balance = 100
years = 0
while balance < 200:
balance *= 1.07 # +7% per year
years += 1
print(years, round(balance, 2))The for loop and range()
for takes each element of a sequence in turn. When you need a set number of repeats, use range(): range(5) gives 0 to 4, and range(2, 8, 2) gives 2, 4, 6.
for fruit in ["apple", "plum", "fig"]:
print(fruit.upper())
for i in range(1, 4):
print(i, "squared is", i * i)
for idx, ch in enumerate("abc"):
print(idx, ch)Loops can be nested. An else attached to a for runs only when the loop finishes without break, which is handy in search tasks.
for n in range(2, 20):
for d in range(2, n):
if n % d == 0:
break
else:
print(n, "is prime")