Python control flow
Created By: chatGPT
In Python, control flow dictates the order in which statements are executed. The if, elif, and else statements are fundamental for controlling the flow of execution based on conditions.
if condition:
# Executes if condition is True
elif another_condition:
# Executes if another_condition is True
else:
# Executes if no conditions are True
You can use comparison operators like
==
, !=
, <
, >
, <=
, and >=
to create conditions. Additionally, logical operators (and
, or
, not
) allow for combining multiple conditions.if age >= 18 and age <= 65:
print('You are an adult of working age.')
else:
print('You are either too young or too old to work.')
For cases where you need to execute a statement multiple times, you can utilize loops such as the for loop and the while loop.
for i in range(5):
print(f'This is iteration number {i}')
A while loop continues as long as its condition is True. Be careful to modify the condition within the loop to avoid an infinite loop.
count = 0
while count < 5:
print(count)
count += 1 # Increment count
Functions can be defined to encapsulate code that controls flow, enabling reusability and helping maintain clean code. You define a function using the
def
keyword.def check_number(num):
if num > 0:
return 'Positive'
elif num < 0:
return 'Negative'
else:
return 'Zero'
You can also use exceptions for error handling, utilizing
try
, except
, and finally
to manage unexpected conditions gracefully.try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print('You cannot divide by zero!')
finally:
print('Execution finished.')