Python If-Else Statements: A Beginner's Guide

Hello there, future Python enthusiasts! Today, we're going to embark on an exciting journey into the world of decision-making in Python. Just like how we make choices in our daily lives, Python programs need to make decisions too. And that's where if-else statements come in handy!

Python - If else

What are If-Else Statements?

Imagine you're a robot (a very smart one, of course) and you need to decide whether to wear a raincoat or not. You'd probably check if it's raining outside, right? That's exactly what if-else statements do in Python - they check a condition and then decide what to do based on whether that condition is true or false.

Basic Structure of an If Statement

Let's start with the simplest form:

if condition:
    # code to execute if condition is True

Here's a real-world example:

is_raining = True

if is_raining:
    print("Don't forget your umbrella!")

In this example, if is_raining is True, the program will print the reminder. If it's False, nothing happens. Simple, right?

Python If-Else Statement

Now, what if we want to do something when the condition is False? That's where the 'else' part comes in:

if condition:
    # code to execute if condition is True
else:
    # code to execute if condition is False

Let's extend our weather example:

is_raining = False

if is_raining:
    print("Don't forget your umbrella!")
else:
    print("Enjoy the sunny day!")

Now our program has two possible outcomes. If it's raining, we get a reminder for our umbrella. If it's not, we're encouraged to enjoy the sun!

Indentation is Key!

One crucial thing to remember in Python is indentation. The code block under each condition must be indented. It's not just for neatness - it's how Python knows which code belongs to which part of the if-else statement.

temperature = 25

if temperature > 30:
    print("It's a hot day!")
    print("Remember to stay hydrated!")
else:
    print("The temperature is pleasant.")
    print("Enjoy your day!")

See how the two print statements under each condition are aligned? That's important!

Python If-Elif-Else Statement

Life isn't always a simple yes or no, and neither are programming conditions. Sometimes we need to check multiple conditions. That's where 'elif' (short for 'else if') comes in handy.

if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition2 is True
else:
    # code to execute if all conditions are False

Let's see this in action with a more complex weather scenario:

temperature = 28

if temperature > 30:
    print("It's a hot day! Stay cool and hydrated.")
elif temperature > 20:
    print("It's a nice warm day. Enjoy!")
elif temperature > 10:
    print("It's a bit cool. Maybe bring a jacket.")
else:
    print("It's cold out there. Wrap up warm!")

This program checks multiple temperature ranges and gives appropriate advice for each. The 'else' at the end catches any temperature that didn't meet the previous conditions.

The Order Matters!

When using if-elif-else, the order of your conditions is crucial. Python checks the conditions from top to bottom and executes the code for the first True condition it finds. After that, it skips the rest of the statement.

Consider this example:

score = 85

if score >= 60:
    print("You passed!")
elif score >= 80:
    print("You did great!")
else:
    print("You need to study more.")

Even though the score is 85, which meets both conditions, only "You passed!" will be printed because it's the first True condition Python encounters.

To fix this, we should reorder our conditions:

score = 85

if score >= 80:
    print("You did great!")
elif score >= 60:
    print("You passed!")
else:
    print("You need to study more.")

Now it correctly prints "You did great!"

Nested If Statements

Sometimes, you might need to check for conditions within conditions. This is where nested if statements come in handy:

has_ticket = True
bag_weight = 22

if has_ticket:
    print("You have a ticket. Let's check your bag.")
    if bag_weight <= 20:
        print("Your bag is within the weight limit. Have a nice flight!")
    else:
        print("Your bag is overweight. Please pay the extra fee.")
else:
    print("Sorry, you need a ticket to board the plane.")

In this example, we first check if the person has a ticket. If they do, we then check their bag weight. This allows for more complex decision-making processes.

Comparison Operators

When working with if-else statements, you'll often use comparison operators. Here's a quick reference table:

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Logical Operators

Sometimes you need to combine conditions. That's where logical operators come in:

Operator Meaning
and Both conditions must be True
or At least one condition must be True
not Inverts the condition

Here's an example using logical operators:

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can rent a car.")
elif age >= 18 and not has_license:
    print("You're old enough, but you need a license.")
else:
    print("Sorry, you must be 18 or older to rent a car.")

This checks both the age and license status before making a decision.

Conclusion

And there you have it, folks! You've just taken your first steps into the world of decision-making in Python. Remember, practice makes perfect. Try creating your own if-else statements, experiment with different conditions, and soon you'll be making Python programs that can handle all sorts of situations.

Happy coding, and may your programs always make the right decisions!

Credits: Image by storyset