Python If Else: An In-Depth Guide to If-Else Statements in Python
Python is one of the best languages to learn for someone new to programming. It’s powerful, flexible, and most importantly, extremely easy to read. Unlike Java or C, which look like Martian hieroglyphics, Python looks almost like English. Prime example of this is the if-else statement, which reads almost like an if-else statement in everyday English.
If-else is a conditional statement, sometimes also called a “control flow” statement. These statements enable the programmer to make decisions and direct the user’s ‘path’ through the program. A mastery of if-else statements is crucial whether you’re programming in Python or any other language.
In this tutorial, we’ll learn everything about the if-else statement in Python, its syntax, and how it can be used with plenty of examples. For a more in-depth examination of the if-else statement in Python, try this excellent course on Python for beginners.
Before We Begin: Tutorial Requirements
This tutorial assumes that you’re already familiar with basic Python syntax. Namely, I expect you to:
- Understand what variables and lists are and how to define them.
- Use simple commands like print and return.
- Use and manipulate text (strings) and numbers.
- Execute a Python program in the command prompt
We’ll create some fairly lengthy programs through the course of this tutorialOf course, you’ll also need Python installed on your computer. If you’re using a Mac or Linux, you should already have Python installed (to check, just head over to the command prompt and type in ‘python’). Else, head over to Python.org and grab a copy of v2.7 (see how I used an if-else statement in the last sentence?).
This tutorial was written on a Windows machine, though you should have no trouble translating the code used to OS X or Linux. In terms of software, I used Notepad++ as the text editor, and Windows Powershell to execute the programs.
Methodology and Expectations
The best way to learn programming is by actually doing it. While I’ll introduce you to the syntax and explain how if-else statements work, you’ll learn a lot more if you try out each of the included examples yourself. Don’t just copy-paste code; type-it out, each letter at a time. Fiddle around with the code, see how you can improve it, what you can cut down on, and what other features can you add to it. The golden rule of programming, to quote Mark Zuckerberg, is to “move fast and break things”.
With that out of the way, let’s get started with the tutorial!
If-Else statements in Python
The if-else statement is a staple of most programming languages. It is used to test different conditions and execute code accordingly. You can think of it as a ‘map’ used to make decisions in the program.
The basic syntax is as follows:
if condition1 = True: execute code1 else: execute code2
In plain English, this can be described as follows:
“If condition1 is true, then execute the code included in code1. If it is not true, then run code2”
A few things to note about the syntax:
- Each if/else statement must close with a colon (:)
- Code to be executed as part of any if/else statement must be indented by four spaces, equivalent to one press of the Tab key.
- Although not explicitly required, every if statement must also include an else statement – it just makes for a better program.
You use if-else statements a lot in your every day. Virtually every decision you make involves some form of if-else statements. “If the bacon is cheap, I’ll buy a pound. If not, I’ll grab some mac and cheese”, “if I wake up before 6, I’ll head out for a jog. Otherwise, I’ll head straight to work”, and “if the traffic is light, we’ll make the movie theater in time. Else, we’ll just have to grab dinner and go back home” – these are some simple if-else decisions we’ve all made in our everyday life. Thus, by using if-else statements in Python, you give the program the ability to make decisions depending on the user input.
But enough talk; let’s try to understand if-else statements with an example:
x = 5 if x > 5: print "X is larger than five!" else: print "X is smaller than or equal to five!"
Head over to the Windows Powershell and run the program. This is what you should see:
If we change the value of x to 6, the output changes as well:
Breaking it down, this program basically instructs Python to:
- Check the value of x.
- If the value of x is more than 5, print that “X is larger than five”.
- If the value of x is less than or equal to 5, print “X is smaller than or equal to five”.
As we’ll learn below, the decision making capabilities of if-else conditions will come very handy when you want to create complicated programs.
Testing Multiple Conditions with Elif
The above if-else syntax is great if you want to test just one condition, but what happens when you want to check multiple conditions?
This is where the Elif statement comes in handy.
Elif is a shortened form of Else-If. The syntax can be seen as follows:
if condition1 = True: execute code1 elif condition2 = True: execute code2 else: execute code3
In plain English, you can read this as follows:
“If condition1 is true, execute code1. Else, if condition2 is true, execute code2. If neither condition1 or condition2 are true, execute code3.”
There is no limit to the number of elif statements you can include in a Python program. You can test dozens of conditions using multiple elif statements as long as you close with an else statement.
Let’s try to understand this with an example:
x = 5 if x == 5: print "Wow, X is EXACTLY five!" elif x > 5: print "X is now MORE than five!" else: print "X is now LESS than five!"
When run, this program will give the following output:
Change the value of x to 6 and the output changes as well:
Reduce x to 4, however, and the third block of code under else comes into play as follows:
So what exactly is happening here?
Let’s break it down into individual steps:
- Python first checks if the value of x is exactly equal to 5, as given in the first if statement.
- If x is equal to five, Python executes the code included within the first if statement and exits the program.
- If, however, x is not equal to 5, Python goes to the second elif statement. It now checks if x is greater than 5.
- In case x is more than 5, Python executes the second block of code under the elif statement and exits the program.
- However, if both conditions are not met, that is, x is neither equal to, nor greater than five, Python displays the output under the third else statement.
As mentioned above, an if-else conditional block can include as many elif statements as you want.
Confused by if-else statements? Learn how to master Python in this ultimate Python programming tutorial.
Nested If-Else Statements
So far, we’ve used just a single level of if-else statements. But what if you want to make decisions within decisions? That’s like saying: “if the oranges are fresh, buy a dozen if they are more than $5/lb, and two dozen if they are less than $5/lb”
In programmer-speak (i.e. algorithmically) this can be written as follows:
orange_quality = “fresh” orange_price = 4.0 if orange_quality == “fresh”: if orange_price < 5: buy 24.0 else: buy 12.0 else: don’t_buy_oranges
This is an example of a nested if-else statement – an if-else statement inside another if-else statement. These can help you make more complex decisions and give you even finer control over the program flow. In terms of syntax, they can be written as follows:
if condition1 = True: if condition2 = True: execute code1 elif condition3 = True: execute code2 else: execute code3 else: execute code4
Thus, the syntax rules are the same as a standard if-statement – i.e. nested statements must be tabbed in. Theoretically, you can nest as many if-else statements as you want, but it is poor practice to go more than two levels deep. If you really need to go deeper than that, you should consider moving some of the decision making to a separate function.
Enough syntax and theory. Let’s look at an example:
In this example, we will:
- Ask the user to enter a number between 1 and 20.
- Verify that the number is less than 20.
- Once verified, square the number if it is even, or multiply it by 3 if it is odd.
This may sound complicated, but by using nested if-else statements, it’s quite easy to do
(Hint: to find out whether a number is even, use the modulo (%) operator. If the modulo of a number and 2 is 0, the number is even. If it is one, the number is odd, since any odd number divided by 2 will yield 1 as the remainder).
Enter the following code in your text editor:
print "Please enter a number between 1 and 20" enter_num = int(raw_input("> ")) #int() added to ensure that the input is treated as a number, not a string if enter_num >= 1 and enter_num <= 20: #conditional statement that ensures limit is between 1 and 20. print "You have entered a valid number" if enter_num % 2 == 0: #test for even/odd print "Your number is even" print enter_num * enter_num elif enter_num % 2 == 1: #test for even/odd print "Your number is odd" print enter_num * 3 else: print "You've entered an invalid number"
This is the result when we enter ‘18’ as our number:
And the result with ‘13’ as the number:
This works wonderfully well, but it’s also a prime example of a situation where we don’t need to use nested if-else statements. Many amateur programmers have a tendency to over-nest if-else statements which can lead to all sorts of problems with larger programs.
For your homework, try to simplify the above program so it fits into a single if-else statement. Remember that you can use ‘AND’ and ‘OR’ to include multiple conditions within a single statement.
If you get stuck here’s a hint:
if enter_num >= 1 and enter_num <= 20 and enter_num % 2 == 0:
Combining If-Else Statements with Loops
So far, we’ve made some fairly basic programs using only if-else statements. While this can help create all sorts of interesting programs, you won’t unleash the full power of if-else statements until you combine them with loops – both for and while loops.
Loops in Python are a fairly advanced concept, but also fundamental to Python, or any other programming language for that matter. You can learn more about for loops in Python in the next tutorial in this series.
For now, let’s consider an example that shows how if-else statements can be combined with loops.
Let’s say we have a list of positive and negative numbers and we want to print only the negative numbers from the list. Since we have a list, we’ll need to use a for loop to go through each item in the list. Combined with an if statement, we can create this program as follows:
number_list = [21, -13, 14, -8, 9, 0, -0.5] #creates a list of numbers for num in number_list: #goes through each number (num) in the number list if num < 0: #checks whether number is negative print num
Here’s the output:
So far, we’ve learned all the theory there is to know about if-else statements in Python. But to really grasp the capabilities and limits of if-else statements, we’ll take a look at a number of examples.
Examples and Exercises
1. Create a program that checks whether a user name belongs to a list of authorized users
This is a very simple program that will utilizes an important operator – in. The in operator in Python checks whether a value belongs to an existing list or not. It’s very useful when working with lists and dictionaries. We’ll use it in this example to check whether our input user name belongs to an existing list or not.
Here’s the program:
authorized_users = ["george", "john”, "paul", "ringo"] #create list of authorized users user_name = raw_input("Please enter your user name here: ") #ask for user input if user_name in authorized_users: #check whether user input is a part of authorized users list print "Access granted" else: print "We've issued a security alert"
And here’s the result:
We’ll cover exit(0) in the example below, so ignore that for now. The important thing to note here is the in operator.
2. Opening and reading a file with specific text
Most programs you’ll create will need you to work with files, either new or existing. In this particular problem, we’ll create a copy of the file only if it contains some specific text, say, (spoiler alert!) “Luke, I am your father”.
To do this, we’ll have to take the following steps:
- Open an existing file.
- Read the contents of the file.
- Take desired action if and only if the contents of the file match our specified text. In this case, we’ll add the specified text to the file if it is not present already.
Let’s get started:
First, create a text file with some sample text and place it in the same directory as your program. It may or may not include our specified text, “Luke, I am your father”.
Next, write down this program:
print "We are first going to ask the user to open the desired file" print "Please enter the name of the file you want to open" filename = raw_input("> ") print "We'll now open the file" target_file = open(filename, 'a+') print "Reading the file" read_file = target_file.read() print "Printing contents of file" print read_file print "Let's check the length of the file" print "The target file is %d bytes" % len(read_file) print "Checking whether specified text can be found in file" txt = "Luke, I am your father" if txt in read_file: print "Text found in target file" target_file.close() else: print "Text not found in file." print "Adding text" file = open(filename, 'a+') file.write(txt) file.close()
The result when the specified text is already present in the file:
And the result when text is not present in the file:
A few things to note here:
- We used ‘a+’ when opening the file. This is called an opening ‘mode’. Opening the file with ‘a+’ means that you can both read and write to the file, and all the new content will be added to the end of the file. Find out what other modes you can use when opening the file. This Stackoverflow question has some good answers.
- We first used open then read. Find out what happens if we use a mode like ‘w’, which is for writing to the file only, and use the read command.
- We used the inbuilt len function to check the length of the file in terms of bytes.
- We used close to successfully close to file following the operation.
3. Creating a simple text adventure
We’ve seen how if-else statements can be used to test multiple conditions and make decisions. But how can we use these statements in an actual, useful program?
For this final example, we’ll create a simple text adventure game that will take some input from the user and return different results depending on the input. We’ll design the game from the ground up and list out each and every component before we create a single line of code. The purpose of this exercise is not just to illustrate what you can do with if-else statements, but also how software design ought to be approached.
The basic requirements of the game are as follows:
- Ask for and accept a user name (player name).
- Create four rooms or scenes – a forest, a castle, a gold room and a dragon room – with multiple action choices.
- Exit the program in case of an incorrect choice.
Based on the above requirements, we can approach our program design as follows:
- Store the player’s name in a separate variable
- Import the ‘exit’ module to exit the program safely.
- Create individual functions for each room. Ask for user input such that making the appropriate choice will take you to a particular room.
We can now create our program from the design approach we adopted above. Type in the following code into your text editor:
from sys import argv from sys import exit #importing argv and exit modules script, user_name = argv def start(): #defining different functions at the very start next = raw_input("> ") if next == "START" or next == "start": forest() else: print "I'm sorry, I don't understand this command" start() def dead(reason): print "You are dead because", reason exit(0) def forest(): print "You find yourself in a cold dark forest." print "There is a light ahead in the clearing." print "What do you do - move forward, or run away?" next = raw_input("> ") if next == "MOVE FORWARD" or next == "move forward" or next == "Move forward": castle() elif next == "RUN AWAY" or next == "run away" or next == "Run away": dead("you ran away!") else: print "I'm sorry, I don't understand this command" forest() def castle(): print "You are now standing before a mighty castle." print "There are two doors before you." print "Door #1 is old, rusty and covered with moss." print "Door #2 is white, radiant and brighter than the morning sun." print "Which door do you take?" next = raw_input("> ") if next == "1" or next == "one" or next == "#1": gold_room() elif next == "2" or next == "two" or next == "#2": dragon_room() else: print "I'm sorry, I don't understand that command" castle() def gold_room(): print "You are now in a room filled with gold coins." print "How many gold coins will you take?" print "Be careful - the Gods of the castle do not reward the greedy!" next = int(raw_input("> ")) if next < 100: print "You were not greedy!" print "Congratulations, you won the game!" exit(0) elif next > 100: print "A trap door opens and you fall into a pit filled with spikes!" dead("you got greedy!") else: gold_room() def dragon_room(): print "You find yourself facing a huge dragon!" print "You can either fight or flee!" print "What do you do?" next = raw_input("> ") if next == "fight" or next == "Fight" or next == "FIGHT": dead("you tried to fight a mighty dragon with your bare hands!") elif next == "flee" or next == "FLEE" or next == "Flee": print "You run back to the safety of the castle!" castle() else: dead("you took too long to decide!") print "Welcome to the %s program %s!" % (script, user_name) print "What should we call you? "player_name = raw_input("> ") print "Thank you for playing the game, %s" % player_name print "Please type in START to begin the game!" start()
Now head over to the Powershell and enter the following into the command prompt:
This will start the program with the user_name as ‘player1’. The program will now ask you for a player name of your choice:
After you’ve chosen a player name, you can START the program.
So it begins! You first find yourself in a forest clearing. You have the option to ‘move forward’ or ‘run away’. Since we’re all Python pioneers here, let’s choose ‘move forward’:
You are now standing before a mighty castle. You have the option of choose between two doors.
Great, since you chose door #1, you are now in a large room filled with gold. Depending on the choice you make, you may win the game, or end up dead.
That’s it – we’ve come to the end of our little text adventure. Admittedly, it’s not much in the way of ‘adventure’, but it has introduced you to the possibilities of ‘if-else’ statements and making decisions in Python.
Now, play the game again, but this time, choose different choices – ‘run away’ instead of ‘move forward’, door #2 instead of #1, etc. What different results do you see?
Understanding the Program
We’ve done quite a few interesting things in this program. Some of them may have left you scratching your head. We’ll take a look at the program structure in a little more detail below:
from sys import argv from sys import exit
If you know your Python, you would know that the from command is used to import modules into the program. Here, we are importing two commands – argv and exit from the sys module.
- argv is called ‘argument variable’. It’s like a standard variable, except that you can pass it in the command line itself. The variable can then be used later in the program.
- exit is used to exit the program. Look it up on Python documentation online to see what arguments you can use with it.
script, user_name = argv
Here, we are creating two variables as argument variables. The first, script, will hold the name of our program (in this case, example.py). The second, user_name, will hold the name of the player (player1).
def start(): next = raw_input("> ") if next == "START" or next == "start": forest() else: print "I'm sorry, I don't understand this command" start()
You know that the def command is used to define functions. Here, we are defining a new function called ‘start’ which we will call upon later in the program. We will accept an input using the raw_input command and hold it in a variable called ‘next’. Depending on the input entered in ‘next’, we will either proceed to the first scene (forest) or restart the program.
For homework, try to find answers to the following questions:
- If you typed the complete program, you know we use the ‘next’ variable multiple times. How is this possible? Is there a difference between global variables passed outside functions and local variables passed within specific functions?
- Look up the global command in python documentation online.
- Why did we use if next == “START” or next == “start”:? Did we really need to enter both uppercase and lowercase variations of ‘start’? Find out what happens when you enter ‘Start’.
def dead(reason): print "You are dead because", reason exit(0)
Since we will be exiting the program regularly based on the choices the player makes, we created a separate function called dead which we can call upon to exit the program when required. A couple of things to note here:
- def dead(reason) means that the dead() function must have at least when argument when used. Find out what will happen if you use the dead() function but don’t include anything between the parenthesis.
- exit(0) is used to exit the program. Find out what (0) in the exit command stands for. What will happen if we used exit(1)? The online python documentation should be of help.
We created separate functions for different ‘rooms’. It’s a good practice in software design to create individual functions for most actions. This helps with debugging, especially when your programs become a little too complicated.
else: print "I'm sorry, I don't understand this command" forest()
By referencing the forest() function within the function itself, we are essentially creating a loop. If the conditions in either of the above two if and elif statements aren’t met, this loop will ensure that the program goes back to step 1 – i.e. ask for user input and assign it to the ‘next’ variable.
When we move to the castle() function, we notice the following code:
if next == "1" or next == "one" or next == "#1":
Find out why we enclosed the number 1 inside double quotes (thus, making it a string). What will happen if we were to change ‘next == “1”’ to ‘next == 1’?
On a similar note, look at the code in gold_room():
next = int(raw_input("> "))
Here, we turned raw_input into an integer by wrapping it between int(). This is necessary because in the subsequent code, we are comparing numbers.
if next < 100:
If we’d use the raw_input, ‘next’ would have been a string. As you would know, you can’t compare a string with a number, making our condition, next < 100, redundant.
Go ahead and remove the int() and see what happens to the program.
A few questions to ponder over we move on to the next part of this tutorial:
- There are plenty of shortcomings in this program. For example, unless you type ‘move forward’ exactly as shown in the instructions, the program will return an error. Find out how you can overcome this shortcoming and allow the player to use normal, conversational language (hint: lookup Python dictionaries and lists).
- Why did we define the functions before writing the actual program? Is this always a good practice? Why? Why not? What if you created functions as and when you required them in the program?
- Did we really need to create two separate variables for user_name and player_name?
You should now have a beginner’s grasp of if-else statements in Python and how to use them effectively. We’ll end with a few frequently asked questions and a list of courses you can take to expand your Python knowledge.
Frequently Asked Questions
Q. How many spaces must an if-else code block be indented by?
Four spaces, equivalent to a single press of the Tab key in most text editors. Remember that every if-else level must be indented by four spaces.
Q. Must an if-statement always include an else statement?
Not quite, though it is considered poor practice if you don’t include an else statement. This is not only because it makes your code readable, it also reduces errors in case the condition in the if statement is not fulfilled. As they say, it’s better to be safe than sorry.
Q. How many elif statements can I include in an if-else block?
As many as required. You can test as many conditions as you want on separate elif lines as long as you don’t break the syntax (colon at the end and indented by four spaces).
Q. Must every if statement begin on a new line?
In the examples above, we started each if statement on a new line. If you look at code sources online, you’ll find the same practice repeated in most programs. However, Python does support single-line if statements, provided there is only one line in the body of the statement, like the example given below:
x = 6 if x == 5: print "X is five" else: print "X is not five"
The only discernible advantage of such single-line statements is brevity. It doesn’t make for very clean code and the practice is frowned upon unless you are really in a hurry. For most cases, stick to multiple line if statements starting on new lines.
Q. What is a tuple?
A tuple is used to store values in Python. Think of it as a list, except that the values are enclosed between round brackets (), unlike lists which use square brackets . Values stored in tuples can’t be changed.
Here’s an example of a tuple:
def tuple_test(i): if i in (10, 20, 100): #Values stored within the round brackets make up a tuple print "Value matches" else: print "Value doesn't match" tuple_test(10) tuple_test(100) tuple_test(5)
Essentially, we used the tuple to compare the variable to multiple values. Else, we would’ve had to write something like:
if i == 10 or i == 20 or i == 100 print “Value matches”
Tuple makes it possible to test multiple values at the same time. Not only does it make for less typing, it also improves program performance. A program that uses tuples will be faster than one that uses complicated if-else statements. While performance won’t be an issue right now, it becomes a major problem as your program grows in complexity.
Tip: To find out how long a program takes to run, use the built-in time() function.
Q. Where can I learn more about Python commands, functions and features?
The best place to learn about Python is at the official Python documentation at docs.python.org. This will tell you everything about the syntax, features and capabilities of different Python commands.
You can also learn about specific commands and features using the pydoc command in command prompt. Say, you want to learn more about the raw_input command. On Windows, type this into the command prompt:
python –m pydoc raw_input
But if this is too technical for you (and it is a little technical), head over to websites like Stackoverflow to seek answers, or simply Google your command.
You now know the basics of if-else statements in Python. Your next step should be to learn about loops, understand dictionaries, and finally, master classes and object oriented programming in Python. These courses listed below will help you get off on the right foot:
- Learn web programming with Python
- Master Python and Python Django
- Python for complete beginners
- Intermediate level Python
Besides these courses, keep on practicing Python basics, try to create your own problems, and read code whenever you can.
Top courses in Python
Python students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.