Python Documentation

Control Flow

Control Flow in Python

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.

If-Else Statements

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

For Loops

Used for iterating over a sequence (like a list, tuple, dictionary, set, or string).

for item in sequence:
ㅤ# code to execute for each item

While Loops

Used to execute a set of statements as long as a condition is true.

while condition:
ㅤ# code to execute while condition is True

Break and Continue Statements

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

Try-Except Statements

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

With Statements

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.