Chapter 1.9 - Input and variable types

Until now we have learned that we can interact with Python using the CLI interface. But entering Python code at the >>> prompt is slow and can only be done one line at a time. It is also not possible to save the code so that another person can run it. Thankfully, there is an even better way to enter Python code.

Python code can be entered using a script. A script is a series of lines of Python code that will be executed all at once.

In spyder3 you can write a series of commands in the editor window and save them as a script. 

Let's say that we would like to calculate the kilometers per liter that a car achieves.

A simple program would be

k = 253 # we have traveled 253km
g = 15.2 # we have used 15.2 liters of gasoline
kpg = k / g
print ("Kilometers per liter: ", kpg)

This script could be even more useful if it would interact with the user asking the users to input the variables. This can be done with the input statement. We will also use better name for the variables so we would not need comments to explain what the variables are representing. See the code below.

# This code almost works
kilometers_driven = input("Enter kilometers driven: ")
liters_used = input("Enter liters used: ")
kpl = kilometers_driven / liters_used
print("Kilometers per liter: ", kpl)

Why this code produces an error? This is because the program does not know the user will be entering numbers. The user might enter “Bob” and “Mary”. 

To tell the computer these are numbers, it is necessary to surround the input function with an int( ) or a float( ). Use the former for integers, and the latter for floating point numbers.

# Calculate kilometers Per Liter
print("This program calculates kpl.")
# Get kilometers driven from the user
kilometers_driven = input("Enter kilometers driven: ")
# Convert text entered to a floating point number
kilometers_driven = float(kilometers_driven)
# Get liters used from the user
liters_used = input("Enter liters used: ")
# Convert text entered to a floating point number
liters_used = float(liters_used)
# Calculate and print the answer
kpl = kilometers_driven / liters_used
print("Kilometers per liter: ", kpl)

How can we find what type is a variable? We can use the command type. Try the following code sequentially in the command line entering a floating point number (ex. 34.5).

a = input("Enter a number : ")
print (a)
type (a)
a = float(a)
print (a)
type(a)