Python Input


The input function is the easiest way to be able to acquire user input in Python. This opens a whole world of possiblities, because you can now use a user's input in your computations.

Basic Usage with Variables

First we will look at the simplest way you can use the input function. This is done by assigning the value of a variable to the input function. Variables can be read about here. This will create an area in the console where the user can type in a value, which is then saved into the assigned variable. For example:

greeting_response=input("Hello, how are you\n")

This will create this message in the console, which you can then type a response to.
Note: "\n" is called an escape character and creates a new line in the console.

Hello, how are you

What has now happened here is the value of "Great" has been saved into our original variable from above, greeting_response. And we can see if we print the value of the variable:



This variable can then be manipulated just like any other variable.


One important thing to take notice of, however, is that the value of any variable populated by the input function is initially a string. This means, as you can read about in the articles on Arithmetic and String Arithmetic here and here, that mathematical operations cannot be performed on any numbers acquired with the input function. For example:

age=input("How old are you?\n")
print("In four years you will be",age+4)

If this code is ran, a type error will occur. This is because on the second line, we are trying to add a string, age, and an integer, 4. To get around this, whenever we need to ask the user for a number value, we can use what is called a type cast. This will convert the input to whatever type we like. For example, this code will not produce a type error:

age=input("How old are you?\n")
print("In four years you will be",age)

Notice the int() surrounding age on the second line. This instataneously converts that value to an integer. An error is then not produced, as we are adding an integer with an integer. It must be noted that using the int() type cast on value that cannot be an integer such as a string like "Hello" will produce a value error.

Other type casts for different types can be written as:



Now you have the ability to accept input from the user. This means you can start manipulating the data they give you in any way you like. Perhaps perform some mathematical operation for them, or modify text they entered to create an interesting word. Whatever it is, I encourage you to try making any small program to practice this idea.