Conditionals and Loops
Conditionals and Loops
if / elif / else
Blocks are defined by indentation (usually 4 spaces). No parentheses around the condition required.
pythonscore = 75 if score >= 70: print(\"Passed\") else: print(\"Failed\")
Chain with elif:
pythonif score >= 90: grade = \"A\" elif score >= 80: grade = \"B\" elif score >= 70: grade = \"C\" else: grade = \"F\"
for loop
Iterate over a sequence (e.g. a list or range):
pythonfor i in range(5): print(i) # 0, 1, 2, 3, 4 for item in [\"a\", \"b\", \"c\"]: print(item)
range(n) gives 0 to n-1. Use range(start, end) or range(start, end, step) for more control.
while loop
pythonn = 0 while n < 3: print(n) n += 1
Use break to exit and continue to skip to the next iteration.