Python If-Else Statements: A Complete Guide

In Python, you can introduce logic to your code with if-else statements.

You can use if-else statements to build decision-making capabilities for your program.

For example:

age = 10

if age > 17:
    print("You can drive.")
else:
    print("You cannot drive!")

When you run this piece of code, it tells whether or not you can drive based on your age. Because the age is 10, the program tells you cannot drive yet:

You cannot drive!

This is a simple example of an if-else statement in Python.

If-else logic is one of the fundamental building blocks in Python. Basically, every program you ever build will use lots of if-else logic. It’s important to understand how the if-else logic works.

This guide teaches you everything you need to know about if-else statements in Python. After reading this guide, you know:

  • How to represent the truth in Python
  • How to introduce decision-making into your code
  • How to check multiple conditions with if-elif-else statements
  • How to add if-else statements inside an if-else statement

Let’s start by learning how you can represent the truth in Python.

Boolean Values: Representing the Truth in Python

In Python, there are two logical values to represent the truth. These are True and False. These truth values are also known as boolean values.

The boolean values build the foundation for introducing logic to your code.

When you check for equality or run other types of comparisons in your code, you will get a boolean value as a result. Speaking of comparisons, I’m assuming you are already familiar with the comparison operators. For reference, here are the six comparison operators of Python:

  • == for equal to
  • != for not equal to
  • < for less than
  • <= for less than or equal to
  • > for greater than
  • >= for greater than or equal to

Here are some examples of comparisons that return boolean values as results:

print(1 < 2)
print(10 == 10)
print(10 >= 100)

Output:

True
True
False

To introduce logic into your code, you need to use the boolean values in if-else statements. For example, you might want to run a piece of code only if number A is greater than number B.

Let’s start with the most basic decision-making statement, that is, the if statement.

If Statements

In Python, you can use an if-statement to check if a condition holds. In other words, if the condition is True, you can run an action.

If the condition is not True, you can skip running the action.

Here is the blueprint for creating an if-statement in Python:

if condition:
    #actions

Where:

  • The condition is a boolean value, that is usually a result of a comparison, such as 1 < 2.
  • If the condition evaluates True, the code execution continues into the if-block where it says #actions. You can replace the #action with any valid Python code. The code can expand to multiple lines.

Notice that the code inside the if-statement needs to be indented. This tells Python that the code lives inside the if-block and only runs if the condition is True. If you don’t indent the code, Python thinks it lives outside of the if-statement. This means the code will always run regardless of the outcome of the if-check.

As you’ve learned, your Python code is executed from top to bottom. Whenever Python encounters an if-statement, it checks the condition and only runs the code inside the if-block if the condition is True.

The best way to learn Python is by doing some examples. So here is one. Let’s print a message to the console only if it’s cloudy today. Here is the code:

cloudy = True

if cloudy == True:
    print("Sun doesn't shine today.")

If you run this little program, you can see the following message in the console:

Sun doesn't shine today.

This is because the cloudy variable is set to True and you use the if-statement to see if that’s the case.

An if-statement like the above is the most basic example of introducing conditional logic to your code. Typically, the if-statement also has an else-statement that performs an action if the if-statement condition is not True.

If-Else Statements

In Python, an if-else statement runs code based on a condition.

Here is the blueprint for creating if-else statements in Python:

if condition:
    #true-actions
else:
    #false-actions
  • If the checked condition is True, the code in the if-block is executed.
  • If the checked condition is not True, the code in the else block is executed.

Here is a flowchart that shows how your Python program sees the if-else statements.

Python if else true false illustration

This illustrates the behavior of an if-else statement well. The code checks if a condition is True. If it is, the corresponding code is executed. If the condition is False, then another piece of code is executed.

But the best way to learn this is by working with some examples.

For instance, let’s create a program that tells whether you are old enough to drive a car.

myage = 20

if myage < 18:
    print("You cannot drive a car")
else:
    print("You can drive a car!")

If you run this piece of code, you get the following output:

You can drive a car!

Although it might be obvious to you, let’s see why this happened.

  • Python first checks if the condition myage < 18 is True. In other words, the program checks if 20 < 18 is True. Obviously, this is False.
  • Because the condition evaluates False, Python continues to run the code in the else block.

Good! Now you have a basic-level understanding of if-else statements in Python. Before moving on, let’s practice if-else statements and make an important point at the same.

In the previous example, the if-else statement’s condition was a comparison between two numbers. But you can compare anything else, such as strings.

Here’s an example:

name = "Alice"

if name != "Bob":
    print("Welcome to the party!")
else:
    print("You were not invited!")

Output:

Welcome to the party!

This piece of code makes sure a guest’s name is not “Bob” before letting them in.

By the way, if you are performing a check on a value that is boolean, to begin with, you don’t need to compare it to a boolean value. For example, this piece of code checks if a variable sunny is True:

sunny = True

if sunny == True:
    print("Let's go to the beach")
else:
    print("Let's go to movies")

Output:

Let's go to the beach

But instead of writing sunny == True as the condition in the if-else statement, it’s enough to write the name of the boolean variable without the comparison:

sunny = True

if sunny:
    print("Let's go to the beach")
else:
    print("Let's go to movies")

Output:

Let's go to the beach

If-Elif-Else Statements

In Python, you can add multiple different conditions in an if-else statement by adding an elif block between the if and else blocks.

Here is the blueprint for creating if-else statements in Python:

if condition2:
    #actions1
elif condition2:
    #actions2
elif condition3:
    #actions3
else:
    #false-actions
  • If the checked condition is True, the code in the if-block is executed.
  • If the if statement’s condition was False, the elif block is executed. If the condition evaluates True, the code inside the elif-block gets executed and the evaluation of the if-elif-else statement terminates.
  • If none of the previous conditions evaluated True, the code in the else block is executed.

Here is an example of an if-elif-else statement:

myage = 17

if myage >= 18:
    print("You cannot drive a car")
elif myage == 17:
    print("Start a driving school")
else:
    print("You can drive a car!")

Output:

Start a driving school

In the above example, the condition in the if-check is False. But the condition checked in the elif block is True. Thus, the code inside that block gets executed.

To take home, you can check additional conditions in an if-else statement with elif statements. You can add as many elif blocks to your if-else statements as you need.

Nested If-Else Statements

In Python, you can place any valid code inside an if-else statement—even another if-else statement.

An if-else statement that lives inside an if-else statement is called a nested if-else statement.

There is nothing special about placing an if-else statement inside an if-else statement. The logic remains the same.

Here is an example:

sunny = True
cold = False

if sunny:
    if cold:
        print("Let's go for a walk.")
    else:
        print("Let's go to the beach.")
else:
    if cold:
        print("Let's go to movies.")
    else:
        print("Let's go fishing.")

Output:

Let's go to the beach.

Multi-Condition If-Else Statements

Thus far, you have dealt with examples of single-condition if-else statements. But more often than not, you want to check multiple conditions at the same time by using logical operators.

By the way, I’m assuming you already know what Python’s logical operators are. For reference, here is a quick list of those:

  1. and. The and operator returns True if both expressions evaluate True.
  2. or. The or operator returns True either one of the expressions evaluate True.
  3. not. The not operator inverts True to False and False to True.

Here are some examples of the logical operators:

print(1 == 1 and 2 == 2)
print(1 < 2 or 2 < 1)
print(not True)

Output:

True
True
False

Let’s take a look at an example of an if-else statement with multiple conditions.

sunny = True
cold = False

if sunny and cold:
    print("Let's go for a walk.")
elif sunny and not cold:
    print("Let's go to the beach.")
elif not sunny and cold:
    print("Let's go to movies.")
else:
    print("Let's go fishing.")

Output:

Let's go to the beach.

As you can see, the above code example reads almost like English:

  • If it’s sunny and cold, let’s go for a walk.
  • If it’s sunny and not cold, let’s go to the beach.
  • If it’s not sunny and cold, let’s just go to the movies.
  • Otherwise, let’s go fishing (i.e. if it’s not sunny and not cold)

Let’s take a look at another example with numbers:

height = 1.5 #meters

if height > 1.3 and height < 2.0:
    print("Welcome to the rollercoaster.")
else:
    print("You must be between 1.3m and 2.0m!")

Output:

Welcome to the rollercoaster.

This piece of code checks that the height is both over 1.3m and less than 2.0m before letting a person sit on a rollercoaster.

A Trick to Simplify Multiple Conditions

One cool “trick” you can do when comparing multiple numbers is to chain the comparison operators. This is useful when you are working with ranges of values.

For example, let’s say you want to check if a number is between 0 and 10. Traditionally, you would do it like this:

x = 7

if x > 0 and x < 10:
    print("The number is between 0 and 10")

Output:

The number is between 0 and 10

But if you look at the conditions x > 0 and x < 10, it takes a second to understand what it means. This is where chaining the operators comes in handy. Instead of writing the conditions like above, you can do it in a much neater way:

x = 7

if 0 < x < 10:
    print("The number is between 0 and 10")

Output:

The number is between 0 and 10

Now the condition is much more readable. You can instantly see that the check is about figuring out if a number is between 0 and 10. This is also the way you normally denote ranges in maths.

At this point, I’ve shown you everything you need to understand about if-else statements in Python. I’m sure there’s a lot of information to digest. I’d suggest playing with all the examples above and changing the code and logic.

If you are not overwhelmed by the information above, I’m going to show you two more things:

  1. One-liner if-else statements. This is a trick to make if-else statements shorter.
  2. Match-case statements. These offer a replacement for specific types of if-else statements to make code more readable.

One-Line If-Else Statements

In Python, you can write single-expression if-else statements as one-liners. Whether you should do it or not is up for debate. Some people consider saving four lines of code worth it. Others think one-liner expressions only make the readability worse.

Anyway, here’s the “trick”. Instead of writing an if-else statement like this:

if condition:
    #true_expr
else:
    #else_expr

You can replace it by:

#true_expr if condition else #else_expr

Let’s see an example of applying this in practice. Here is a traditional if-else statement:

age = 10

if age < 18:
    message = "No driving"
else:
    message = "You can drive"

And here is a shorter replacement for the exact same logic:

age = 10
message = "no driving" if age < 18 else "You can drive"

The one-liner if-else statement is not a Python-only thing. It’s present in many popular programming languages, such as JavaScript and Swift. It’s commonly called the ternary operator or the ternary conditional operator.

But before you use it, remember to think about the code quality. Only use such shorthand if it improves the code readability and quality. If the code has fewer lines but you can’t make anything of it, then you are doing it wrong.

Of course, if you are a beginner programmer, it’s way too early to think too much about code quality. But it’s good to keep in mind one should always write code that is easy to understand. When you work as a software developer, writing clean code is vital to developing software at scale.

If-Else Replacement: Match-Case Statements

To make the code in this section work, you must have Python 3.10+. With earlier versions, you get a SyntaxError.

In Python, you can use if-else statements to introduce decision-making capabilities to your program. You are going to need if-else statements throughout your career as a software developer.

But in some cases, lengthy if-elif-else chains become rather verbose and unreadable. Here is an example of such a mess:

day = "Monday"
if day == "Sunday":
    print("Take it easy")
elif day == "Monday":
    print("Go to work")
elif day == "Tuesday":
    print("Work + Hobbies")
elif day == "Wednesday":
    print("Meetings")
elif day == "Thursday":
    print("Presentations")
elif day == "Friday":
    print("Interviews and party")
elif day == "Saturday":
    print("Time to do sports")

Here, the day == “something” repeats over and over again. The code looks repetitive and lengthy.

In a situation like this, you might find match-case statements more useful. When using a match-case structure, the above code turns into this:

day = "Monday"
match day:
    case "Sunday": print("Take it easy")
    case "Monday": print("Go to work")
    case "Tuesday": print("Work + Hobbies")
    case "Wednesday": print("Meetings")
    case "Thursday": print("Presentations")
    case "Friday": print("Interviews and party")
    case "Saturday": print("Time to do sports")

The idea of a match-case statement is to match the compared object with a pattern and code corresponding to that pattern.

For example, in the above code, the match-case statement takes the day variable and tries to match it with “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, and “Saturday”. Because the day is “Monday”, it matches with the case “Monday” and runs the code attached to it.

Read more about the match-case statements.

Conclusion

Today you learned what are if-else statements in Python.

To recap, you can introduce logic to your code with if-else statements.

With if-else the program can make decisions based on conditions.

The most basic version of checking a condition is by using an if-statement. When Python sees an if-statement, it checks if the condition holds and performs an action if it does. If the condition doesn’t hold, no action will take place and the program execution continues unaltered.

cloudy = True

if cloudy == True:
    print("Sun doesn't shine today.")

The most usual way to check conditions is by using an if-else statement. If the condition is True, some code gets executed. If the condition is False, then some other code gets executed.

age = 10

if age > 17:
    print("You can drive.")
else:
    print("You cannot drive!")

If you have a lot of related conditions checked, you can add elif blocks to your if-else statements.

This way you can specify actions to take for each condition.

myage = 17

if myage >= 18:
    print("You cannot drive a car")
elif myage == 17:
    print("Start a driving school")
else:
    print("You can drive a car!")

Thanks for reading. Happy coding!

Scroll to Top