Python · Control flow: if, for, while
if/elif/else, for loops over iterables with range, enumerate and zip, while loops, and break/continue/else.
if / elif / elsepicks a branch.for x in iterableloops over the items of anything iterable. To get index numbers, userange(n), orenumerate(seq)when you need the index and the item together.zip(a, b)walks two sequences side by side.while condrepeats as long as the condition is true.breakexits the loop andcontinueskips to the next iteration.- A loop’s
else:block runs only if the loop finished withoutbreak. That’s handy for searches.
for n in [7, 12, 0]:
if n == 0:
kind = "zero"
elif n % 2 == 0:
kind = "even"
else:
kind = "odd"
print(n, kind)
subjects = ["maths", "physics", "python"]
scores = [88, 79, 95]
for i, (s, m) in enumerate(zip(subjects, scores), start=1):
print(i, s, m)
# first prime above 90, using while + for/else
n = 90
while True:
n += 1
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
print("first prime above 90:", n)
break
Output:
7 odd
12 even
0 zero
1 maths 88
2 physics 79
3 python 95
first prime above 90: 97Sources
- More Control Flow Tools — Python Software Foundation
- Built-in functions: enumerate — Python Software Foundation
- Built-in functions: zip — Python Software Foundation