Conditional statements:
score = 72
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: C
The for loop iterates over any iterable, such as lists, strings, ranges, and dicts:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Use range() to loop a specific number of times
for i in range(5): # 0 1 2 3 4
print(i)
for i in range(1, 10, 2): # 1 3 5 7 9 (start, stop, step)
print(i)
# Enumerate gives index and value together
for idx, fruit in enumerate(fruits):
print(f"{idx}: {fruit}")
The while loop runs as long as a condition is true. Use break to exit early and continue to skip to the next iteration:
n = 10
while n > 0:
if n % 2 == 0:
n -= 1
continue # skip even numbers
print(n)
n -= 1