Python Programming

Control Flow: Conditions and Loops

30 دقيقة

if / elif / else

score = 82
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"

One-line form for simple choices: label = "pass" if score >= 50 else "fail".

match (Python 3.10+)

match command.split():
    case ["go", direction]:
        move(direction)
    case ["quit"]:
        stop()
    case _:
        print("Unknown command")

for loops

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

for i in range(1, 6):          # 1..5
    print(i)

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

for name, score in zip(names, scores):
    print(name, score)

while loops

attempts = 0
while attempts < 3:
    password = input("Password: ")
    if password == "secret":
        break                  # leave the loop
    attempts += 1
else:
    print("Locked out")        # runs only if the loop did not break

continue skips to the next iteration.

Comprehensions

A compact way to build lists, dicts and sets:

squares = [n * n for n in range(10)]
evens = [n for n in numbers if n % 2 == 0]
lengths = {word: len(word) for word in words}
unique_domains = {email.split("@")[1] for email in emails}

Use them for simple transformations; switch to a normal loop when logic grows.

Useful built-ins with loops

sum(prices)          max(scores)          min(scores)
any(x < 0 for x in values)                # True if any is negative
all(item.paid for item in orders)          # True if all are paid
sorted(users, key=lambda u: u.age, reverse=True)

Worked example: FizzBuzz

for n in range(1, 101):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Exercise

Write a number-guessing game: pick random.randint(1, 100), let the user guess with hints "higher"/"lower", count attempts and stop after 7 tries.

Check yourself

  • When does a loop's else block run?
  • Rewrite [n for n in range(20) if n % 3 == 0] as a normal loop.
  • What does any() return for an empty list?

يُحفظ تقدّمك في هذا المتصفح فقط.

إرسال للمراجعة (10 نقطة)