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:
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
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
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")
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! :)