Control flow statements allow you to control the execution of code based on certain conditions and to repeat code. The main control flow statements in Python are:
- Conditional Statements:
if
,elif
,else
. - Loops:
for
Loop: Iterates over a sequence (like a list, tuple, string).while
Loop: Repeats as long as a condition is true.
Conditional Statements Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
elif age == 17:
print("You can apply for early registration.")
else:
print("You are not eligible to vote.")
Loops Example:
# For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While loop
count = 0
while count < 5:
print("Count:", count)
count += 1