Functions

Input

Now comes some real fun with the input function! input allows us to prompt the user to give us some sort of data to use in our program. Now our programs can be interactive! Interactive = more fun for sure. :)

A quick example:

name = input("What's your name, little buddy?")
print(f"Hi there {name}!")

Let’s see how this works.

$ python3 greetings.py
What's your name, little buddy?

At this point the program pauses for the user to input something.

What's your name, little buddy?Ginger
Hi there Ginger!

That input line looks a little awkward since Python prints the prompt exactly as we type it, so let’s add a space after the question mark.

name = input("What's your name, little buddy? ")
print(f"Hi there {name}!")
$ python3 greetings.py
What's your name, little buddy? Ginger
Hi there Ginger!

Nice!

Let’s try out adding a couple of numbers together in a program called add.py:

number1 = input("What is the first number you would like to add? ")
number2 = input("What is the second number you would like to add? ")

sum = number1 + number2

print(f"The sum is {sum}")
$python3 add.py
What is the first number you would like to add? 4
What is the second number you would like to add? 4
The sum is 44

Well, that’s not what we were going for. Why? If we think back to when we were looking at adding things together in the REPL, adding numbers gave us the sum of the numbers, but adding strings concatenated—smashed together—the strings. Could that be what’s happening here?

We can use the type() function in Python to investigate. Let’s change add.py momentarily.

number1 = input("What is the first number you would like to add? ")
number2 = input("What is the second number you would like to add? ")

print(type(number1))
print(type(number2))
$ python3 add.py
What is the first number you would like to add? 4
What is the second number you would like to add? 4
<class 'str'>
<class 'str'>

They’re strings! Data given to the input function are strings by default. We can convert them to floating point numbers using float().

number1 = input("What is the first number you would like to add? ")
number2 = input("What is the second number you would like to add? ")

total = float(number1) + float(number2)

print(f'The sum is {total}')
$ python3 add.py
What is the first number you would like to add? 4
What is the second number you would like to add? 4
The sum is 8.0

Neat! We could also convert to a floating point number using float() while we’re assigning the input to a variable.

number1 = float(input("What is the first number you would like to add? "))
number2 = float(input("What is the second number you would like to add? "))

total = number1 + number2

print(f'The sum is {total}')