input() and Standard In


A program that runs in the terminal is called a "console program" (console and terminal are practically synonyms). These console programs can become much more interactive if we learn a way for the user to give us some "input". Python has a simple function for doing so, the aptly named input function.

def hello():
    print('hello there')
    user_status = input('how are you? ')
    print('you said: ' + user_status)

def main():
    hello()

Input in the Terminal

Here is example of running the above hello.py in the terminal. In this example the text written by the user is in blue.

$ python hello.py
hello there
how are you? I am fine
you said: I am fine

Changing variable types

When you call the input function, the response entered by the user is given back to you! It is always "returned" as a value of type "str" also known as a string. That is a problem if you want to do any further computation. For example, lets say you wanted to print the value a user entered divided by two. You open up the Python interpreter and run the following code:

>>> x = input('enter a value: ')
enter a value: 42
>>> print(x)
42
>>> print(x/2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

This is subtle, but recall that every variable has a type. Even though x looks like a number, its type is string. Recall that input always returns a string. The interpreter is complaining that it doesn't make sense to divide a string! Now that you know what the issue is, the fix is simple. You just need to change the variable type to be a float or an int. To do so you can use functions called float and int.

>>> x_float = float(x)
>>> print(x_float/2)
21.0
We can call x_float anything we like. I put the term "float" in the name simply so that you can understand the type just by reading the name.

 


Python Reader