If-Else in Python: Explained with Examples!

In this article let’s see how to write if-else statements in Python.

All programming languages have a way of writing if-else statements, which is just a way of making a decision on what to do next!

If it rains, open the umbrella!

embeddedinventor.com

Here the decision of “whether or not to open the umbrella” is made based on the condition that “it rains“.

Though this example may seem like a “real world” one as opposed to a “programming world” one, the idea is the same!

For example

if (password == "abcd1234"):
    print("Logging in!")
else:
    print("Please try again")

Here the decision of “whether or not to let us into the computer” is made based on the condition that the “password is correct

The syntax (or grammar) used in Python for writing if-else code is shown below.

if <condition>:
  <execute the statements here is the condition is "true">
else:
  <execute the statements here if the condition is "false">

Don’t forget to add the colon “:” at the end of the lines with “if” and “else“, else you will end up with a SyntaxError!

Also, keep in mind that the lines that are inside if and else blocks must be “indented“. In other words, we must leave some space between the start of the line and the actual code. The recommended indentation is 4 spaces.

Let us see this syntax in action one more time.

Here various parts of the syntax are color coded to match each other!

Now that we have got the syntax down, let’s get some practice by seeing some more examples!

if-else in Action!

Let’s look at more examples to see the if-else statement in action!

Example#1 Comparing strings

fruit = "apple"

if fruit == "orange":
    print("Your fruit is an orange!")
else:
    print("Your fruit is NOT an orange!")

This will produce the following output as the condition “fruit == orange” is False since our fruit is an apple (See line-1)

Your fruit is NOT an orange!

If the fruit was orange, then the if block will be executed as the condition will be satisfied:

fruit = "orange"

if fruit == "orange":
    print("Your fruit is an orange!")
else:
    print("Your fruit is NOT an orange!")

and you will get this output instead

Your fruit is an orange!

Example#2 Checking an element in a list

nums = [1, 2, 3, 4, 5]

if 3 in nums:
    print("3 is in the list")

In this example, we have a list of numbers called nums that contains numbers from 1 to 5. We check if the number ‘3’ exists in the list and since the condition is True we get the following output

3 is in the list

Example#3 Checking the capitalization of a string

word = 'HELLO'

if word.isupper():
    print("Your word is uppercase")

In this program, the .isupper() method is used to check whether a given string is uppercased. Since the string is clearly uppercased, the condition is determined True and the if block is executed:

Your word is uppercase

Checking Multiple conditions one after another

There is one more Keyword we need to learn other than if and else which is used in the example below.

if fruit == "orange":
    print("Peel before eating!")
elif fruit == "apple":
    print("No need to peel!)

Here the elif keyword is short for “else if” and this can be used in situations where you might need to check multiple conditions one after another.

There might also be situations when we might need to deal with multiple conditions, but instead of dealing with them one after another, we have to deal with them all at the same time. Check out the article below to learn more!

Python “if” Statement with Multiple Conditions: Explained with Examples!

If you are a visual learner, be sure to check out the following video we made on a related topic!

Challenges

Theory will only get you so far. The best way to learn anything is by practice, here are some challenges that will help you understand better everything that we covered today:

  1. Write a program that determines if a number is even
  2. Write a program that determines if a number is a positive number
  3. Get a letter from the user, check if the letter is uppercased, and print a message accordingly

And that’s a wrap, dear reader! I hope you have understood everything I explained today!

Kudos to you for sticking to the end! Not many have the patience and curiosity that you have!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends!

Related Articles

Python if with 2 conditions: Explained with Examples!

Python if with 3 conditions: Explained with Examples!

Figuring out if “break” was used to exit the loop in Python

Python “if” Statement with Multiple Conditions: Explained with Examples!

Python: “if not true” How to write? Explained with Examples!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn