Control Flow
Control flow in Python refers to the order in which individual statements, instructions, or function calls are executed in a program. Python provides several control flow structures to manage the flow of your program.
Used for conditional execution of code blocks.
if condition:
ㅤ# code to execute if condition is True
elif another_condition:
ㅤ# code to execute if another_condition is True
else:
ㅤ# code to execute if all conditions are False
Used for iterating over a sequence (like a list, tuple, dictionary, set, or string).
for item in sequence:
ㅤ# code to execute for each item
Used to execute a set of statements as long as a condition is true.
while condition:
ㅤ# code to execute while condition is True
Used to alter the flow of loops.
for item in sequence:
ㅤif condition:
ㅤㅤbreak # exit the loop
ㅤif another_condition:
ㅤㅤㅤcontinue # skip to the next iteration
Used for exception handling.
try:
ㅤ# code that might raise an exception
except ExceptionType:
ㅤ# code to handle the exception
else:
ㅤ# code to run if no exception was raised
finally:
ㅤ# code that always runs, regardless of exceptions
Used for resource management (like file handling).
with open('file.txt', 'r') as file:
ㅤcontent = file.read()
ㅤ# file is automatically closed after this block
These control flow structures allow you to create complex logic in your Python programs, controlling how and when different parts of your code are executed.