Working With If Statements In Python

avatar
(Edited)

Back for another article on getting started with Python programming. We didn't get any work done on our check savings program in our last post but we did a thorough run down of Loops in Python and introduced you to If Statements.

This article is going to give you the full details on If Statements and we will then add them into our savings program. So far, we have two separate programs, one to add savings, and another to check savings. Our goal is to combine the two programs and provide the user with a menu system that will ask the user to make a selection and allow them to perform different tasks from the one program.

It may be easier if we start with a new program that will do the following:

  1. Provide the user with a set of choices in a menu
  2. Allow the user to make a choice
  3. Verify the choice is valid
  4. Allow the user to perform the selected task
  5. Return to the start when the selected task has been performed

Indentation In Python


Just before we start our new code I need to make something clear about indentation in Python. We haven't mentioned this yet, but indentation is very, very, very important as it denotes blocks of code. Other programming languages use things like curly brackets or semi colons to denote blocks of code. In Python on the other hand, we use white space. So far we haven't really needed to point this out as the code we have been running is very limited, but in the following page, you will need to make sure you are paying attention to make sure the indentation for your code is consistent. We will be doing our best to point this out as we run through our code.

Start with a Loop


In our last article we discussed Loops and this will be the perfect way to present a menu to the user. If you start by creating a new file called python_savings.py that will be our main program that will be run.

touch python_savings.py

We will start off coding the program with the following code, which will start our program off and present the user with a menu of tasks to be performed. As you can see line 4 has a While Loop that will continually run as it is set to True, it then prints out a set of text to the user including our three choices the user can make. Line 11 then asks the user to make a selection and stores it in the variable named "choice" which is then presented in line 12.

  1 #!/usr/bin/env python
  2
  3 # Welcome the user and provide a menu
  4 while True:
  5   print("Welcome to Python Savings.")
  6   print("Choose from one of the tasks below.")
  7   print("1. Add Savings.")
  8   print("2. View Savings.")
  9   print("3. Quit Program.")
 10
 11   choice = input("From the items above make a select from 1 - 3: ")
 12   print("You picked {}".format(choice))

Our code doesn't really do any work as yet, but is a nice start. There are a few problems though as it keeps going without stopping and we need to press Ctrl C to kill the program. Below is an example of the program being run below. We can select numbers other than 1, 2 or 3 without letting the user know the selection is not valid as well. We need to do something about that.

Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 2
You picked 2
Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 4
You picked 4
Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: Traceback (most recent call last):
  File "C:\python_savings.py", line 11, in <module>
    choice = input("From the items above make a select from 1 - 3: ")
KeyboardInterrupt

Introducing If Statements


Our program menu has presented us with the need to test what the user is entering and verify if it is a value option or not. This is the perfect way for use to use an If Statement which we only touched on for a moment in our last article. If statements are used to allow you to control the flow of the program and allow users to make specific decisions. These statements can be simply presented as:

  • One test with one "if"
  • One test with one "if" statement, and a default "else" statement for False tests.
  • One multiple tests with one "if", one or more "elif" and a default "else" statement for False tests.

The simplest form of the if statement is the following where we have a single condition. If the condition is tested and is True, the indented statement in the next line is then performed, and if the test is False, it simply returns to the rest of the Python code:

As you can see in the example below, the colon(:) separates the test condition from the statement that is run, if the condition is true. Also note the indentation from the condition and the statement.

if (condition):
   indented statement

In our last article, we started using the break statement in our While Loop and this is exactly the same as our example above.

>>> while True:
...   print("Infinite Loop Runs Once")
...   if True:
...     break
...
Infinite Loop Runs Once

We only have one test condition and if that is true it runs, false it does not run and continues on with the rest of the program.

We can then add an else statement to perform a statement if condition is false:

if (condition):
  statement if condition is true
else:
  statement if condition is false

Below is a simple example where we have set the value of a variable named "test" and our condition is to see if this variable is equal to the number 7.

>>> test = 8
>>> if (test == 7):
...   print("The variable is equal to 7")
... else:
...   print("The variable is not equal to 7")
...
The variable is not equal to 7

All that is left to do is use the "elif" statement. This is when we want to test for more than one condition. Make sure you are spelling it correctly, it is definitely ELIF, and as you can see below, we have set a new condition. We can also add as many "elif" statements if you want.

if (condition):
  statement if condition is true
elif (another condition)
else:
  statement if all conditions are false

NOTE: We have been putting out condition into brackets for each of our examples, but this is not actually needed. By placing it in brackets, I personally feel it separates condition from the rest of the code and is why I always use it. In the example below, both if statements are the same, but when you get more complex examples, you might need to include the brackets to chain different conditions together.

if (True):
  print("True") 
# Is the same as
if True:
  print("True")

This will be perfect for our new user menu we set up earlier. If we add the following code to the end of our Loop, we can now put in place a nice IF/ELIF/ELSE statement as we have below. As you can see, we have two conditions, one is equal to 3 and the loop breaks causing the program to finish, and the second is to verify the number is less than 3 to be a valid selection.

 13   
 14   if (int(choice) == 3):
 15     break
 16   elif (int(choice) < 3):
 17     print("\nYou picked {}\n".format(choice))
 18   else:
 20     print("\nYou have made an invalid choice, please try again\n")

This lets our program run a little nicer:

python .\python_savings.py
Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 1

You picked 1

Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 6

You have made an invalid choice, please try again

Welcome to Python Savings.
Choose from one of the tasks below.
1. Add Savings.
2. View Savings.
3. Quit Program.
From the items above make a select from 1 - 3: 3

Nesting If Statements


The code above is looking better, but we still have an extra If Statement to add. The code below is the complete code so far for our python_savings.py program. At line 16, you will notice we have added an extra If Statement, inside another If Statement. This is called nesting. We use the Elif condition to make sure we have a valid choice, and then we decide between the two choices to provide the user with their valid selection.

  1 #!/usr/bin/env python
  2
  3 # Welcome the user and provide a menu
  4 while True:
  5   print("Welcome to Python Savings.")
  6   print("Choose from one of the tasks below.")
  7   print("1. Add Savings.")
  8   print("2. View Savings.")
  9   print("3. Quit Program.")
 10
 11   choice = input("From the items above make a select from 1 - 3: ")
 12
 13   if (int(choice) == 3):
 14     break
 15   elif (int(choice) < 3):
 16     if (int(choice) == 1):
 17       print("\nYou picked {}\n".format(choice))
 18     else:
 19       total = 0
 20       f = open("savings.txt", "r")
 21       savings_from_file = f.readlines()
 22       f.close()
 23
 24       for i in savings_from_file:
 25         total += int(i)
 26       print("\nI have saved ${} so far this year\n".format(total))
 27   else:
 28     print("\nYou have made an invalid choice, please try again\n")

This Code Is Now In Git


Our code has been pretty small so far, but it is starting to get a little more complex so we have set up a GitHub repository to now store our code.

At the following location you will be able to see the repository we have set up for these tutorials:
https://github.com/vincesesto/python_study.git

This repository will have links to all the articles we have made so far and we will also be storing all the code for future articles.

Some more really good progress here and you may have noticed that we didn't add the code to add savings into our application. This is why our program is looking a little confusing at the moment and it is about time we introduced readers to Functions. This should allow us to organise our code a little better and will start to allow us to reuse our code as well. So make sure you see our next article coming soon.

Found this post useful? Kindly tap the up vote button below! :)

About The Author


I am a DevOps Engineer, Endurance Athlete and Author. As a DevOps Engineer I specialize in Linux and Open Source Applications. Particularly interested in Search Marketing and Analytic’s, and is currently developing my skills in devops, continuous integration, security, and development(Python).

Posted with STEMGeeks



0
0
0.000
4 comments
avatar

Loops and conditions are what make programming powerful. Some knowledge of logic may be required.

I see you put the conditions in (...), which is not strictly necessary. I have seen others do this and it may be habit as other languages require it.

I won't get into the spaces vs tabs indenting argument, but consistency is the most important thing.

0
0
0.000
avatar

Hey @steevc thanks for your comments and thanks for bringing up about conditions needing to be in brackets. I have actually amended the article to include a note about adding brackets for the conditions as well.
Really appreciate you taking the time to mention that as it really helps.
Regards Vince

0
0
0.000
avatar

No problem. It's useful for me to read through these to see what I can learn.

!BEER

0
0
0.000