Practical Examples of Control Flow in Python
Let’s apply what we learned about if, elif, else, and nested conditions to real-life problems.
Introduction
Control flow allows us to make programs that can decide what to do based on conditions. Here are some practical examples that combine everything we learned so far.
Example 1: Check Voting Eligibility
age = int(input("Enter your age: "))
citizen = input("Are you a citizen? (yes/no): ")
if age >= 18:
if citizen.lower() == "yes":
print("You are eligible to vote.")
else:
print("Sorry, only citizens can vote.")
else:
print("You are not old enough to vote.")
✅ Demonstrates nested conditions and string comparison.
Example 2: Student Grading System
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 50:
print("Grade: B")
else:
print("Fail")
✅ Demonstrates if-elif-else ladder.
Example 3: Positive, Negative, or Zero
num = int(input("Enter a number: "))
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
else:
print("Positive Odd Number")
elif num &lp; 0:
print("Negative Number")
else:
print("Zero")
✅ Demonstrates nested conditions with modulus operator.
Example 4: Simple Login System
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin":
if password == "1234":
print("Login successful!")
else:
print("Wrong password!")
else:
print("No such user found.")
✅ Demonstrates nested checks for authentication.
Common Mistakes
- Forgetting to convert input:
input()returns text. Example:
Comparing with a number:age = input("Enter age: ")
Correct way:if age >= 18: # ❌ Errorage = int(input("Enter age: ")) - Using capitalized keywords:
If,Elif,Else→ ❌ Error. Must be lowercase. - Indentation mistakes: Forgetting to indent after
ifcausesIndentationError.
💡 Practice Challenges
- Write a program that asks for three numbers and prints the largest one.
- Write a program that checks if a given year is a leap year.
- Create a program that asks for a username and password. If correct, print "Welcome", otherwise print "Try again".
What’s Next?
After mastering control flow, we will move on to Loops in Python (for and while). Loops make your code repeat tasks without writing them again and again.
No comments:
Post a Comment