Sahaj.blogs
8 Sept 2023 · StudyPhase 1 · Python

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 / else picks a branch.
  • for x in iterable loops over the items of anything iterable. To get index numbers, use range(n), or enumerate(seq) when you need the index and the item together.
  • zip(a, b) walks two sequences side by side.
  • while cond repeats as long as the condition is true.
  • break exits the loop and continue skips to the next iteration.
  • A loop’s else: block runs only if the loop finished without break. 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: 97

#python#control-flow

Sources

  1. More Control Flow Tools — Python Software Foundation
  2. Built-in functions: enumerate — Python Software Foundation
  3. Built-in functions: zip — Python Software Foundation