Basic User Input

Getting information from the user in Python is simple. In many languages, this requires a lot of extra syntax or imports of external libraries. In Python, basic console input is done by using the built-in input function. The input function needs a prompt message for the user as a string:

In [7]:
myName = input("Please enter your name:  ")
print("Hello, (). Welcome to Python!")
Please enter your name:  Alice
Hello, (). Welcome to Python!

If you are reading the jupyter notebook version of this document, you can execute the above cell to enter your own input. I chose to type Alice. When input is ran, the console will pause and wait for the user to press enter. Once this happens, input consumes what was entered in the console and returns the value as a string. This is important to note when you are asking for numerical input! If you try to use it directly without converting it, you will get an exception:

In [11]:
x = input("Please enter a number:  ")
print("{} > {} = {}".format(5, x, 5>x))
Please enter a number:  5
TypeError                                 Traceback (most recent call last)
<ipython-input-11-03f5305d11f3> in <module>()
      1 x = input("Please enter a number:  ")
----> 2 print("{} > {} = {}".format(5, x, 5>x))

TypeError: unorderable types: int() > str()

To fix this, you can convert it directly to the desired datatype. For sake of example, you can assume the user is inputting correct values. We will save handling errors in another lesson.

In [9]:
x = float(input("Please enter a number:  "))
print("{} * {} = {}".format(5, x, 5*x))
Please enter a number:  5.5
5 * 5.5 = 27.5
In [10]:
x = int(input("Please enter a number:  "))
print("{} * {} = {}".format(5, x, 5*x))
Please enter a number:  5
5 * 5 = 25