In Python, control flow dictates the order in which code is executed, primarily managed through conditional statements (if, else, elif) and loops (for, while). These structures allow you to make decisions and repeat code blocks based on conditions.
Python Control Flow
Control flow structures in Python determine how code executes based on conditions and loops.
Conditional Statements
Python uses if
, elif
, and else
statements for decision-making.
num = 10
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Zero")
Loops
Python supports two types of loops: for
and while
.
For Loop
for i in range(5):
print(i)
While Loop
x = 0
while x < 5:
print(x)
x += 1
Breaking and Continuing
The break
statement exits a loop, and the continue
statement skips the current iteration.
for i in range(5):
if i == 3:
break
print(i)