Control flow statements decide how a program executes, which statements run, and how many times they run based on conditions.
Conditional statements are used to make decisions in a program based on conditions.
if → Executes when condition is trueelif → Checks multiple conditionselse → Executes when no condition is trueif condition:
statements
elif condition:
statements
else:
statements
age = 20
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Nested conditions are if statements inside another if statement.
Used when a decision depends on multiple dependent conditions.
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login successful")
else:
print("Wrong password")
else:
print("Invalid username")
Loops are used to repeat a block of code multiple times.
Used when the number of iterations is known.
for variable in sequence:
statements
for i in range(5):
print(i)
names = ["Amit", "Rahul", "Sneha"]
for name in names:
print(name)
Used when the number of iterations is unknown and depends on a condition.
while condition:
statements
count = 1
while count <= 5:
print(count)
count += 1
Stops the loop immediately.
for i in range(1, 10):
if i == 5:
break
print(i)
Skips the current iteration and continues with the next.
for i in range(1, 6):
if i == 3:
continue
print(i)
Acts as a placeholder where a statement is required syntactically.
for i in range(5):
if i == 2:
pass
else:
print(i)
range() generates a sequence of numbers.
range(start, stop, step)
range(5) # 0 to 4
range(1, 6) # 1 to 5
range(1, 10, 2) # Odd numbers
for i in range(1, 6):
print(i)
Pattern programs improve logic building and loop mastery.
*
**
***
****
*****
for i in range(1, 6):
print("*" * i)
*****
****
***
**
*
for i in range(5, 0, -1):
print("*" * i)
1
12
123
1234
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end="")
print()
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
balance = 10000
withdraw = int(input("Enter amount: "))
if withdraw <= balance:
balance -= withdraw
print("Transaction successful")
else:
print("Insufficient balance")
attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == "admin":
print("Login success")
break
attempts -= 1
else:
print("Account locked")
a, b, c = 10, 25, 15
if a > b and a > c:
print("A is largest")
elif b > c:
print("B is largest")
else:
print("C is largest")