Skip to content

if-elif-else Statements in Python: From Beginner to Advanced

if-elif-else statement in Python

The if-elif-else statements in Python are fundamental for decision-making processes. These statements enable your program to execute certain code blocks based on conditions. Think of them as your personal guide at a crossroads, choosing which path to take based on your situation.

Basic Structure of if-elif-else statement

  • if checks a condition. If it’s True, it runs a block of code.
  • elif (which stands for “else if”) is checked if the previous if or elif was False. You can have as many elifs as you need.
  • else runs if all the previous conditions were False.

Example 1: Simple Decision Making (Beginner)

age = 20

if age < 18:
    print("You're a minor.")
elif age >= 18 and age < 60:
    print("You're an adult.")
else:
    print("You're a senior citizen.")

In this example, the code checks the age and categorizes it into minor, adult, or senior citizen.

Example 2: Grading System with if-elif-else statement in Python (Intermediate)

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Here, the code decides the grade based on the score. It’s like an automated grader!

Example 3: User Access Control (Intermediate)

user_role = 'admin'

if user_role == 'admin':
    print("Full access granted.")
elif user_role == 'editor':
    print("Editing rights granted.")
elif user_role == 'viewer':
    print("Viewing rights granted.")
else:
    print("No access rights.")

This one manages access based on user roles. It’s like a digital bouncer at your club!

Example 4: Nested if-elif-else Statements (Intermediate)

score = 75
if score >= 50:
    print("You passed.")
    if score >= 90:
        print("Excellent!")
    elif score >= 75:
        print("Good Job!")
    else:
        print("Just made it!")
else:
    print("You failed.")

This code checks for a pass or fail and then gives qualitative feedback on the passing score.

Example 5: Using if-elif-else with Lists (Advanced)

colors = ["red", "green", "blue"]
choice = "green"
if choice in colors:
    print(f"{choice} is available.")
else:
    print(f"{choice} is not available.")

Here, the program checks if a chosen color is in a list of colors.

Example 6: Comprehensive Example with Dictionaries (Advanced)

user_roles = {'Alice': 'admin', 'Bob': 'editor', 'Charlie': 'viewer'}
user = 'Alice'

if user_roles.get(user) == 'admin':
    print("Full access")
elif user_roles.get(user) == 'editor':
    print("Editing access")
elif user_roles.get(user) == 'viewer':
    print("View access")
else:
    print("No access")

In this advanced example, the script uses a dictionary to manage user roles and access levels.

Remember, Python checks these conditions in order, and once it finds a True condition, it runs that block and skips the rest. It’s a super handy tool to have in your coding toolbox! 🛠️

These examples showcase the versatility of if-elif-else statements in Python, from simple condition checks to more complex logic involving lists and dictionaries. As you progress in Python, these constructs become vital tools in your coding arsenal, enabling you to write efficient and effective code.

Keep exploring and happy coding! 🌟🐍💻

For more details join us: https://behnamooz.com/

Leave a Reply

Your email address will not be published. Required fields are marked *