Beginner's Guide to Python If-Else Statements

Programming might seem like a daunting task at first, but fear not! Python, a popular and beginner-friendly programming language, has a nifty tool called "if-else statements" that can help you make decisions in your code.

In this guide, we'll walk you through the basics of if-else statements in a simple and relatable way, using easy-to-follow examples and clear explanations.

Understanding If-Else Statements

Imagine you're a chef deciding what dish to cook based on the weather outside. If it's raining, you might make a comforting soup; if it's sunny, you'd probably go for a refreshing salad. Similarly, if-else statements help your program make decisions based on certain conditions.

In Python, an if-else statement works like this:

temperature = 25  # Let's say it's 25 degrees Celsius
if temperature > 30:
    print("Phew! It's hot outside!")
    print("The weather is pleasant.")

Expected Output:

The weather is pleasant.

In this example, the program checks if the temperature is greater than 30 degrees. If it is, it prints a hot weather message; otherwise, it prints a pleasant weather message.

Why Do We Need If-Else Statements?

Think of if-else statements as the "choices" your program can make. Without them, your program would be like a robot following a set path without adjusting to different situations. If-else statements give your program the ability to adapt and make smart choices based on real-world situations.

Different Types of If-Else Statements

1. Simple "If" Statement


if condition:
    # Code to execute if the condition is true

Let's start with the simplest type. Imagine you're deciding whether to wear sunglasses when you go outside. If the sun is shining, you'll wear them; otherwise, you won't.

sun_is_shining = True
if sun_is_shining:
    print("Wear sunglasses!")


Wear sunglasses!

2. "If-Else" Statement


if condition:
    # Code to execute if the condition is true
    # Code to execute if the condition is false

Now, let's add a twist. Suppose you want to wear a jacket when it's cold outside, but not when it's warm. Here's how you'd do it with an if-else statement.

temperature = 15
if temperature < 20:
    print("Wear a jacket!")
    print("You're good without a jacket.")


Wear a jacket!

3. "If-Elif-Else" Statement


if condition1:
    # Code to execute if condition1 is true
elif condition2:
    # Code to execute if condition1 is false and condition2 is true
    # Code to execute if both condition1 and condition2 are false

In some situations, you might have more than two choices. Picture a cafe offering discounts based on your age. If you're below 18, you get a student discount; if you're 18 to 30, you get a regular discount; otherwise, you pay the full price.

age = 25
if age < 18:
    print("Student discount applied!")
elif age <= 30:
    print("Regular discount applied!")
    print("Full price, please.")


Regular discount applied!

How They Differ

Each type of if-else statement handles a different number of choices. A simple "if" statement checks one condition and takes one action. An "if-else" statement chooses between two actions. The "if-elif-else" statement, as the name suggests, can handle multiple choices by evaluating conditions one by one.

Real-Life Scenarios and Examples

1. Simple "If"

Scenario: Checking if a number is positive.

number = -7
if number > 0:
    print("It's a positive number!")

The code you provided will not produce any output because the condition number > 0 is False for the given value of number, which is -7. Since the condition is not met, the code block inside the if statement will not be executed, and there will be no output.

2. "If-Else"

Scenario: Determining if a number is even or odd.

number = 12
if number % 2 == 0:
    print("It's an even number!")
    print("It's an odd number!")


It's an even number!

3. "If-Elif-Else"

Scenario: Deciding which fruit someone prefers based on their input.

fruit_choice = input("Choose a fruit: apple, banana, or orange: ").lower()

if fruit_choice == "apple":
    print("You like apples!")
elif fruit_choice == "banana":
    print("You're a banana fan!")
elif fruit_choice == "orange":
    print("Oranges are your thing!")
    print("Hmm, I'm not sure what you like.")

The output of the given code will depend on the user's input. Here are the possible outputs based on different inputs:

  • If the user enters "apple" (case-insensitive), the output will be: "You like apples!"
  • If the user enters "banana" (case-insensitive), the output will be: "You're a banana fan!"
  • If the user enters "orange" (case-insensitive), the output will be: "Oranges are your thing!"
  • If the user enters any other input, the output will be: "Hmm, I'm not sure what you like."

The code takes the user's input, converts it to lowercase using .lower(), and then checks it against the predefined options to determine the appropriate output message.

Exploring Nesting

As you venture further into the world of programming, you'll encounter situations where decisions aren't straightforward and require more intricate handling. This is where the concept of "nesting" comes into play. Nesting involves placing one if-else statement inside another, allowing you to navigate complex decision-making scenarios with finesse and precision.

1. A Peek into Nesting

Imagine you're deciding what clothes to wear based not only on the temperature but also on whether it's a weekday or the weekend. Here's how nesting can help:

temperature = 20
is_weekday = True

if temperature > 25:
    if is_weekday:
        print("Wear light clothes and bring an umbrella.")
        print("It's a warm weekend, enjoy!")
    if is_weekday:
        print("Wear a light jacket.")
        print("Weekend chill, grab your cozy sweater.")


Wear a light jacket.

In this example, there are two levels of decision-making. The outer if-else statement checks the temperature, and the inner if-else statement checks whether it's a weekday or the weekend. Depending on these conditions, the appropriate clothing advice is given.

2. Benefits of Nesting

Nesting if-else statements provides a structured way to tackle more complex scenarios. It's like opening a series of Russian nesting dolls, each revealing a new layer of choices. This approach enhances code readability, making it easier for you and others to understand the logic behind your decisions.

3. Caution: Don't Overdo It!

While nesting can be powerful, excessive nesting can make your code convoluted and hard to follow. It's essential to strike a balance between clear decision-making and maintaining readability. If you find yourself nesting too deeply, it might be worth reconsidering your approach or breaking down your code into smaller functions.

4. Example: Handling User Access

A real-world scenario where nesting shines is user access control. Let's say you're building an app with different levels of access: guest, regular user, and admin. Depending on the user's role, you need to determine what features they can access.

user_role = "admin"
is_logged_in = True

if is_logged_in:
    if user_role == "admin":
        print("Welcome, admin. You have full access.")
    elif user_role == "user":
        print("Hello, user. You can use basic features.")
        print("Hello, guest. Sign up for more features.")
    print("Please log in to access the app.")


Welcome, admin. You have full access.

Nesting if-else statements is your passport to handling complex decision-making in your code. With practice, you'll learn to arrange your conditions like a master puzzle solver, ensuring your program reacts precisely to even the most intricate scenarios. Remember, just as nesting dolls reveal hidden treasures, nested if-else statements unveil the magic of precise programming logic!

Wrapping Up

If-else statements are your programming buddies when it comes to making decisions in your code. By understanding their types and practicing with simple examples, you'll be well on your way to writing smarter and more adaptable programs.

So, next time you need your program to be as smart as you, remember the power of if-else statements!

Happy coding!

Short Notes

  • If-Else Statements: They help your program make decisions based on conditions. If a condition is true, the program takes one action; if false, it takes another action.
  • Types of If-Else Statements:
    • Simple "If": Executes code when a single condition is true.
    • "If-Else": Offers two options - one for a true condition and another for a false condition.
    • "If-Elif-Else": Handles multiple conditions, evaluating them one by one until a true condition is found.
  • Boolean Logic: The foundation of conditions in if-else statements. In boolean logic, "True" represents a valid condition, while "False" represents an invalid one.
  • Nesting: Placing one if-else statement inside another for handling complex scenarios. Provides structured decision-making, enhancing code readability.

Test Your Knowledge

1. What is the purpose of if-else statements?
2. Which type of if-else statement handles multiple conditions by evaluating them one by one?
3. What does "True" represent in boolean logic?
4. What is nesting in programming?
5. When should you consider using nesting in if-else statements?
Kickstart your IT career with NxtWave
Free Demo