A Complete Guide to User Input in Python | by Chaitanya Baweja | Towards Data Science

User input is critical for building interactive programs. Every programming language has its unique implementation of an input interface. C++ has scanf, Java has the Scanner class, and Ruby has gets.
While in most cases, this input stems from the keyboard, other forms like mouse clicks, track-pad, sensors, etc. are also possible.
As always, Python provides a simple framework for getting user input in the form of the input() function.
The input function reads a line from the console, converts it into a string, and returns it.
In this tutorial, we will cover the input() function in detail using a variety of use-cases. We will discuss the several forms in which input can exist and how to parse this input into our required format with the help of code snippets.
input([prompt])
Here,prompt: an optional string argument, used to display a message for the user. Example: ‘Enter Name:’
When the input() function is called, the program flow halts until the user enters some input. The user then adds some information and presses the Enter key. The input function returns to the program with the entered string.
entered_value = input('Enter some value: ')print(entered_value)
Output:
The input function converts all information that it receives into the string format. Let us take a look:
Output:
Enter name: Chaitanya BawejaEnter age: 20data_type of name:  <class 'str'>data_type of age:  <class 'str'>
We used the type function to check the object’s data type. As you can see above, it does not matter whether we enter a number or a character string. Both of them return as string objects.
As input() function returns everything as a string, we need to perform some explicit type-conversion for accepting integers. Here, we will use the int() function.
Output:
Enter first num: 10Enter second num: 5Type of num_1: <class 'int'>Type of num_2: <class 'int'>The sum of given numbers is :  15
int(string) converts the given string to an integer type.
Similarly, we can get a float value using the float() function.
Output:
Enter value: 5.6Type of float_1: <class 'float'>Twice the given numbers is :  11.2
A common issue with type-conversion is the ValueError exception.
When the user enters input that cannot be converted into the given type, we get a ValueError exception.
For example, the user enters a random string for age.
num = int(input('Enter age: '))
Here, the int() function expects an integer value wrapped inside a string. Any other type of value will result in an error. Look what happens when we enter 'nope' as input.
Output:
Enter age: nope---------------------------------------------------------ValueError                    Traceback (most recent call last)<ipython-input-10-1fa1cb611d10> in <module>----> 1 num_1 = int(input('Enter age: '))ValueError: invalid literal for int() with base 10: 'nope'
To ensure that the user enters valid information, we need to handle many such errors that commonly occur with user input. We will use Python Exception Handling for this purpose. Take a look:
Again if we enter 'nope' as input:
Enter a number: nopeThis is not a number.
In the above snippet, if the user enters a non-integer input, the code will raise an exception. This exception is caught by the except statement where we print: ‘This is not a number’.
Because of this try-except block, our program will not crash on wrong user input.
We can use the exception block along with a loop. Thus, the user will be prompted again and again until they provide valid input.
We can also ask for multiple values directly on a single line with only one call to the input() function. For example, let’s get some information about a student from the user and store it in different variables.
Output:
Enter student's name, age and score separated by space:Chaitanya 20 100Student Name: ChaitanyaStudent Age: 20Student Score: 100
Here, we separated the input string by spaces using the split() method.
But what happens when you are not aware of the number of input values?
Let us suppose that you need to enter a list of numbers and return their sum. You are not aware of the number of elements in that list.How do we input this list?
We use both the split and the map function. The split() method will divide the entered string into a list of strings. Then, the map() function will perform the int operation on all the list elements.
Output:
Enter a list of numbers separated by space: 10 20 30 40 50 60Intermediate_list:  ['10', '20', '30', '40', '50', '60']Number List:  [10, 20, 30, 40, 50, 60]List sum: 210
In the code above:
input() returns a string containing numbers separated by spaces.
split() returns a list of strings partitioned on the spaces.
map() performs int() operation on all the list elements and returns a map object.
list() function converts the map object back into a list.
The input() function returns whenever it encounters a newline character (when the user presses Enter key). Thus, if you try to send multi-line information, input() will only return the first line.
To overcome this, we can use for-loop. We get one line of input per iteration and stop when we receive an empty line (‘Press Enter on an empty line’). We combine all these lines in a list.
Output:
Python provides a simple framework for getting user input. The input function reads a line from the console, converts it into a string, and returns it.
The input function converts all information that it receives into the string format. We use type-conversion to convert the input into the required format.
Exceptions occurring due to invalid input can be managed using the try-except block. The split and map functions help input multiple values in the same line.
Chaitanya Baweja aspires to solve real world problems with engineering solutions. Follow his journey on Twitter and Linkedin.