Conditionals and loops

RequiredRequired

Juan Camilo ZúñigaBackend & data developer

Programs decide with if and repeat with for and while.

Conditionals

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

Comparisons chain naturally: 0 <= x < 10. Combine conditions with and, or and not.

for: one step per item

for walks over anything iterable: a list, a string, a range of numbers.

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

for i in range(3):        # 0, 1, 2
    print(i)

for i, fruit in enumerate(["apple", "pear"]):
    print(i, fruit)       # index and item together

Prefer enumerate over range(len(...)) when you need the index.

while: until a condition changes

attempts = 0
while attempts < 3:
    attempts += 1

break leaves the loop and continue jumps to the next round. A loop can have an else block that runs only when it ends without break, which is handy for searches:

for user in users:
    if user.is_admin:
        break
else:
    print("No admin found")