if and else Statements
The if statement executes a block of code when a condition is true. To handle the scenario when the condition is false, use the else clause.
Syntax
if condition:
# Execute this block if condition is True
statement_a1
statement_a2
else:
# Execute this block if condition is False
statement_b1
statement_b2
Example: Checking a Ticket
has_ticket = 1 # 1 represents having a ticket
if has_ticket == 1:
print("Ticket verified. Boarding allowed.")
print("Looking forward to the journey!")
else:
print("No ticket. Boarding denied.")
print("Better luck next time.")
Output with Ticket:
Ticket verified. Boarding allowed.
Looking forward to the journey!
Output without Ticket:
No ticket. Boarding denied.
Better luck next time.
Exercise: Write a program that checks if a knife's blade length is 10 cm or less. If it is, print "Security check passed." Otherwies, print "Item confiscated."
The elif Statement
For checking multiple exclusive conditions sequentially, use elif (short for "else if").
Syntax
if condition_1:
# Block for condition_1
elif condition_2:
# Block for condition_2
elif condition_3:
# Block for condition_3
else:
# Block if no conditions are met
The flow stops at the first condition that evaluates to True.
Example: Grading System
exam_score = 77
if 90 <= exam_score <= 100:
print("Grade: A")
elif 80 <= exam_score < 90:
print("Grade: B")
elif 70 <= exam_score < 80:
print("Grade: C")
elif 60 <= exam_score < 70:
print("Grade: D")
elif 0 <= exam_score < 60:
print("Grade: F")
Note: elif must follow an initial if statement. It can be combined with a final else block.
Nested Conditional Statements
Conditional statements can be placed inside other conditional statements to create more complex logic.
Syntax
if outer_condition:
# Outer block
if inner_condition:
# Inner block
inner_statement
else:
alternative_inner_statement
else:
# Alternative outer block
outer_alternative_statement
Example: Security Check
ticket_status = 1 # 1 means valid ticket
blade_length_cm = 9 # Knife blade length
if ticket_status == 1:
print("Valid ticket. Proceed to security.")
if blade_length_cm < 10:
print("Security clearance granted.")
print("Enjoy your trip!")
else:
print("Security alert: Prohibited item detected.")
print("Police notification required.")
else:
print("Invalid ticket. Entry forbidden.")
Exercise: Simulate boarding a bus. Check if the passenger's card balance is over 2 units. If they board, check if there are vacant seats (seats_available > 0) and print an appropriate message.
while Loops
A while loop repeats a block of code as long as its condition remains True.
Syntax
while condition:
# Loop body
repeated_statement_1
repeated_statement_2
Example: Simple Counter
counter = 0
while counter < 5:
print(f"Iteration number: {counter}")
counter += 1 # Increment counter
Applications
1. Sum of Numbers from 1 to 100
total = 0
num = 1
while num <= 100:
total += num
num += 1
print(f"The cumulative sum from 1 to 100 is: {total}")
2. Sum of Even Numbers from 1 to 100
even_sum = 0
value = 1
while value <= 100:
if value % 2 == 0:
even_sum += value
value += 1
print(f"The sum of even numbers from 1 to 100 is: {even_sum}")
Nested while Loops
A while loop can contain another while loop.
Example: Printing a Pattern
row = 1
while row <= 5:
col = 1
while col <= row:
print("* ", end="")
col += 1
print() # New line after each row
row += 1
Output:
*
* *
* * *
* * * *
* * * * *
Example: Multiplication Table
a = 1
while a <= 9:
b = 1
while b <= a:
product = a * b
print(f"{b}*{a}={product:2d} ", end="")
b += 1
print()
a += 1
for Loops
The for loop iterates over items in a sequence (like a string, list, or range).
Syntax
for element in sequence:
# Code to execute for each element
process(element)
else:
# Optional: executes after loop finishes normally (not via `break`)
final_action()
Example: Iterating Over a String
word = "Python"
for char in word:
print(char)
Loop Control: break and continue
break: Immediately terminates the entire loop.continue: Skips the rest of the current iteration and proceeds to the next one.
break Example
for i in range(10):
if i == 5:
break # Loop stops when i is 5
print(i)
continue Example
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints only odd numbers
Important: break and continue only affect the innermost loop in which they are placed.
Rock-Paper-Scissors Game Example
import random
player_input = input("Enter choice: scissors (0), rock (1), paper (2): ")
player_choice = int(player_input)
computer_choice = random.randint(0, 2)
# Winning conditions: (0,2), (1,0), (2,1)
if (player_choice == 0 and computer_choice == 2) or \
(player_choice == 1 and computer_choice == 0) or \
(player_choice == 2 and computer_choice == 1):
print("You win!")
elif player_choice == computer_choice:
print("It's a tie!")
else:
print("You lose!")