Python Control Structures Cheat Sheet

Python Control Structures Cheat Sheet

Conditional Statements

if Statement
if condition:
    # code block
if-else Statement
if condition:
    # code block if condition is true
else:
    # code block if condition is false
if-elif-else Statement
if condition1:
    # code block if condition1 is true
elif condition2:
    # code block if condition2 is true
else:
    # code block if none of the conditions are true
Nested if Statements
if condition1:
    if condition2:
        # code block if both condition1 and condition2 are true

Exception Handling

try-except Block
try:
    # code block that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # code block to handle the exception
    print("Cannot divide by zero!")
try-except-else Block
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful:", result)
# Output: Division successful: 5.0
try-except-finally Block
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This will always execute.")
# Output: Division successful: 5.0
# Output: This will always execute.

Miscellaneous

ternary Conditional Operator
x = 10
y = 20
max_value = x if x > y else y
print(max_value)
# Output: 20
while-else Statement
i = 0
while i < 5:
    print(i)
    i += 1
else:
    print("Loop is done")
# Output: 0 1 2 3 4
# Output: Loop is done
for-else Statement
for i in range(5):
    print(i)
else:
    print("Loop is done")
# Output: 0 1 2 3 4
# Output: Loop is done

Looping Statements

for Loop
for variable in iterable:
    # code block
Example of for Loop
for i in range(5):
    print(i)
# Output: 0 1 2 3 4
while Loop
while condition:
    # code block
Example of for Loop
for i in range(5):
    print(i)
# Output: 0 1 2 3 4
Nested Loops
for i in range(3):
    for j in range(3):
        print(i, j)

Loop Control Statements

break Statement
for i in range(5):
    if i == 3:
        break
    print(i)
# Output: 0 1 2
continue Statement
for i in range(5):
    if i == 3:
        continue
    print(i)
# Output: 0 1 2 4
pass Statement
for i in range(5):
    if i == 3:
        pass
    print(i)
# Output: 0 1 2 3 4

Comprehensions

List Comprehension
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionary Comprehension
squares = {x: x**2 for x in range(10)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Set Comprehension
squares = {x**2 for x in range(10)}
print(squares)
# Output: {0, 1, 64, 4, 36, 9, 16, 81, 49, 25}
Generator Comprehension
squares = (x**2 for x in range(10))
for square in squares:
    print(square)
# Output: 0 1 4 9 16 25 36 49 64 81