Skip to main content

Control Flow | Python

  • Control Flow | Python
info

Keywords importantes: break, continue e pass

If Statements

x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")

For Loops

info
  • Possuí indice e valor no for
for index,value in range(5):
print(index)

While Loops

count = 0
while count < 5:
print(count)
count += 1

Break Statement

for i in range(10):
if i == 5:
break
print(i)

Continue Statement

for i in range(10):
if i % 2 == 0:
continue
print(i)

Pass Statement

for i in range(10):
if i % 2 == 0:
pass # Do nothing
else:
print(i)

Try-Except

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always execute")

Match Statement (Python 3.10+)

O operador match é usado para correspondência de padrões, semelhante ao switch em outras linguagens.

def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown status"

print(http_status(200)) # Output: OK
print(http_status(404)) # Output: Not Found
print(http_status(123)) # Output: Unknown status