Python Conditional and Loop Statements: if, for, while
Conditional Statements: if
Execute code block 'a' if condition A is met, otherwise execute code block 'b'. This control flow is called a condisional statemant.
Basic Example
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
Multi-Condtiion Example
score = 75
if score >= 90:
print("Excellent")
elif score >= 80:
print("Good")
elif score >= 70:
print("Average")
elif score >= 60:
print("Pass")
else:
print("Fail")
Truthy/Falsy Values
In Python, values evaluate to:
False: None, empty lists/sets/dicts/tuples/strings, 0, FalseTrue: Non-empty sequences, non-zero numbers, True
value = 1
if value:
print("Valid")
Compound Conditions
# AND condition
if condition_a and condition_b:
pass
# OR condition
if condition_a or condition_b:
pass
# NOT condition
if not condition_a:
pass
Loop Statements: for
Iterates over sequence items like lists or strings.
Basic Iteration
phones = ["Apple", "Huawei", "Xiaomi"]
for phone in phones:
print(f"Current phone: {phone}")
Indexed Iteration
for index, phone in enumerate(phones):
print(f"Phone {index + 1}: {phone}")
Loop Control
# Break example
for i in [0, 1, 2]:
if i == 1:
break
print(i)
# Continue example
for i in [0, 1, 2]:
if i == 1:
continue
print(i)
For-Else Structure
for i in [0, 1, 2]:
if i == 1:
continue
print(i)
else:
print("Loop completed normally")
Loop Statements: while
Repeats execution while condition remains true.
Basic While Loop
age = 1
while age <= 3:
print(f"Age {age}: Not ready for school")
age += 1
print("Ready for kindergarten")
Infinite Loop
while True:
# Requires break condition
pass
While-Else Structure
age = 1
while age <= 3:
print(f"Current age: {age}")
age += 1
else:
print("Ready for school")