Pages

Python control flow

 #control flow

# ─────────────────────────────────────────
# 1. if / elif / else
# ─────────────────────────────────────────
x = 10
if x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")


# ─────────────────────────────────────────
# 2. for loop
# ─────────────────────────────────────────
for i in range(5):
print(f"i={i}", end=" ")

print()
# iterate over a list
for item in ["a", "b", "c"]:
print(item)


# ─────────────────────────────────────────
# 3. while loop
# ─────────────────────────────────────────
count = 0
while count < 3:
print(f"count={count}",end=" ")
count += 1

print()
# ─────────────────────────────────────────
# 4. break, continue, pass
# ─────────────────────────────────────────
for n in range(10):
if n == 3:
continue # skip 3
if n == 6:
break # stop at 6
print(n)

for _ in range(5):
pass # placeholder, does nothing


# ─────────────────────────────────────────
# 5. for / while with else
# ─────────────────────────────────────────
print()
for i in range(3):
print(i)
else:
print("loop finished without break")


# ─────────────────────────────────────────
# 6. match / case (structural pattern matching, Python 3.10+)
# ─────────────────────────────────────────
command = "quit"
match command:
case "quit":
print("quitting")
case "go" | "move":
print("moving")
case _:
print("unknown command")


# ─────────────────────────────────────────
# 7. try / except / else / finally
# ─────────────────────────────────────────
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"caught: {e}")
else:
print("no exception")
finally:
print("always runs")


# ─────────────────────────────────────────
# 8. with statement (context manager)
# ─────────────────────────────────────────
with open("/dev/null", "w") as f:
f.write("hello") # file is auto-closed after the block


# ─────────────────────────────────────────
# 9. comprehensions (inline control flow)
# ─────────────────────────────────────────
squares = [x**2 for x in range(5)]
print(squares)
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
square_map = {x: x**2 for x in range(5)}
print(square_map)
unique_even = {x for x in [1, 2, 2, 3, 4] if x % 2 == 0}
gen = (x**2 for x in range(5)) # generator expression
print(gen)

# ─────────────────────────────────────────
# 10. ternary (conditional expression)
# ─────────────────────────────────────────
label = "even" if x % 2 == 0 else "odd"

No comments:

Post a Comment

Please comment below to feedback or ask questions.