To take user input in Python, we use input() function in Python Programming Language, it asks for an input from the user and returns a string value, no matter what value you have entered, all values will be considered as strings values.
What’s Python User Input and Why We Need It in Python?
Almost all interesting programs accept input from the user at some point. You can start accepting user input in your programs by using the input() function in Python. The input function displays a message to the user describing the kind of input you are looking for, and then it waits for the user to enter a value.
We need input () function in Python because In most of your Python programs you will want to interact with the end-user by asking questions and retrieving user inputs. To do so you can use the input() function in Python.
There are hardly any programs without any input. Input can come in various ways, for example from a database, another computer, mouse inputs and movements or from the internet. Yet, in most cases, the input stems from the keyboard. For this purpose, Python provides the function input(). input has an optional parameter, which is the prompt string.
How to read input from Keyboard in Python?
Python User Input in Python 2
In Python 2 we can read input from standard input device i.e. the keyboard using the following two built-in functions. But as we all know the official support to Python 2 is ended. So it’s better to learn Python 3 now.
raw_input
input
But as we all know the official support to Python 2 is ended. So it’s better to learn Python 3 now.
Python User Input in Python 3
In Python 3 to take input from the user, we use the input
function to read the user input from the standard input (keyboard).
Taking Input Using raw_input ( ) Function
A function is defined as a block of organized, reusable code used to perform a single, related action. Python has many built-in functions; you can also create your own. Python has an input function which lets you ask a user for some text input. You call this function to tell the program to stop and wait for the user to key in the data. In Python 2, you have a built-in function raw_input()
In Python 2.7, you need to use raw_input(). This function reads only one line from the standard input and returns it as a string by default.
If you are using python 2, then we need to use raw_input() instead of input() function.
Note: raw_input() function is decommissioned in Python 3.
Example of Python User Input Using raw_input()
value = raw_input(“Please enter the value: ”)
print(“Input received from the user is: ”, value)
Output:
Please enter the value: Hello Python
Input received from the user is: Hello Python
Taking Input Using input ( ) Function
To take input in Python, we use input() function, it asks for an input from the user and returns a string value, no matter what value you have entered, all values will be considered as strings values.
To get user input in Python (3), the command you use is input()
. Store the result in a variable, and use it to your heart’s content. Remember that the result you get from the user will be a string, even if they enter a number.
For example,
name = input("Give me your name: ")
print("Your name is " + name)
What this will print in the terminal (or the shell, whatever you are running Python in) will be:
>>> Give me your name: Michele
Your name is Michele
What happens at the end of input()
is that it waits for the user to type something and press ENTER. Only after the user presses ENTER does the program continue.
Example of Python User Input Using input() Function
Example 1 of Python User Input
username = input("Enter username:")
print("Username is: " + username)
Output:
Enter username: Python Pool
Username is: Python Pool
Example 2 of Python User Input
val1 = input("Enter any value: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))
val2 = input("Enter another value: ")
print("value of val2: ", val2)
print("type of val2: ", type(val2))
val3 = input("Enter another value: ")
print("value of val3: ", val3)
print("type of val3: ", type(val3))
Output
Enter any value: 10 value of val1: 10 type of val1: <class 'str'> Enter another value: 10.23 value of val2: 10.23 type of val2: <class 'str'> Enter another value: Hello value of val3: Hello type of val3: <class 'str'>
See the program and output – Here, we provided three value “10” for val1 which is an integer value but considered as a string, “10.23” for val2 which is a float value but considered as a string, “Hello” for val3 which is a string value.
Accept an Integer as User Input
Example 1 of Integer Python User Input
a = int(input())
b = int(input())
s = a + b
print(s)
Output
56
12
68
Example 2 of Integer Python User Input
a = input('Please Enter the first number = ')
b = input('Enter the second number = ')
c = int(a) + int(b)
print("Summation of a + b = %s + %s = %s" % ( a, b, c ))
Output:
Please Enter the first number = 45
Enter the second number = 12
Summation of a + b = 45 + 12 = 57
Get Float Input from the user
There is no such method, that can be used to take input as a float directly – but input string can be converted into a float by using float() function which accepts a string or a number and returns a float value.
Thus, we use input() function to read input and convert it into a float using float() function.
Example Taking Python User Input as Float
val1 = input("Enter any number: ") print("value of val1: ", val1) print("type of val1: ", type(val1)) # reading a value, converting to float # printing value and it's type val2 = float(input("Enter any number: ")) print("value of val2: ", val2) print("type of val2: ", type(val2))
Output
Enter any number: 123.456 value of val1: 123.456 type of val1: <class 'str'> Enter any number: 789.123 value of val2: 789.123 type of val2: <class 'float'>
Taking Input from a user in Python as List
Let’s read the inputs one by one. Our application will ask the user to enter the list, the user will enter each input one by one and finally, our application will print out the list entered by the user.
num_list = []
count = int(input("Enter the total count of elements : "))ff
for i in range(0,count):
num_list.append(int(input()))
print(num_list)
In this example,
- num_list is an empty list. We will add all the elements to this list.
- the count is for storing the total count of elements. The second line is asking the user to enter the total number of elements and it stores this value in the count variable.
- Using one for loop, we are reading the elements one by one from the user. These elements are appended to the empty list num_list.
- Finally, we are printing out the list num_list.
Get multiple values from the user
Developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf
but in Python user can take multiple values or inputs in one line by two methods.
split()
method- List comprehension
Using split() method :
This function helps in getting multiple inputs from the user. It breaks the given input by the specified separator. If the separator is not provided then any white space is a separator. Generally, user use a split() method to split a Python string but one can use it in taking multiple inputs.
Syntax :
input().split(separator, maxsplit)
Example :
# Python program showing how to
# multiple input using split
# taking two inputs at a time
x, y = input("Enter a two value: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
print()
# taking three inputs at a time
x, y, z = input("Enter a three value: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
print()
# taking two inputs at a time
a, b = input("Enter a two value: ").split()
print("First number is {} and second number is {}".format(a, b))
print()
# taking multiple inputs at a time
# and type casting using list() function
x = list(map(int, input("Enter a multiple value: ").split()))
print("List of students: ", x)
a) split ()
the split( ) function helps us get multiple inputs from the user and assign them to the respective variables in one line. In addition, this function is generally used to separate a given string into several substrings. However, you can also use it for taking multiple inputs. The function generally breaks the given input by the specified separator and in case the separator is not provided then any white space is considered as a separator.
The syntax for using the split function to take multiple inputs is
variable 1, variable 2 = input ("Enter what has to be conveyed to the user here"). split() # for space-separated inputs
Example of Split
# Python program to take multiple inputs from the user
a, b = input("Enter two of your lucky number: ").split()
print("First lucky number is: ", a)
print("Second lucky number is: ", b)
Output:
Enter two of your lucky number: 7 1
First lucky number is: 7
Second lucky number is: 1
b) input ()
You can take multiple inputs in one single line by using the raw_input function several times as shown below.
#multiple inputs in Python using input
x, y = input("Enter First Name: "), input("Enter Last Name: ")
print("First Name is: ", x)
print("Second Name is: ", y)
Output:
Enter First Name: FACE
Enter Last Name: Prep
First Name is: FACE
Second Name is: Prep
c) map()
map() is another function that will help us take multiple inputs from the user. In general, the syntax for map function is a map (fun, iter). Here fun is the function to which the map function passes each iterable.
The syntax for multiple inputs using map()
variable 1, variable 2, variable 3 = map(int, input().split())
An example to take integer input from the user.
#multiple inputs in Python using map
x, y = map(int, input("Enter two values: ").split())
print("First Number is: ", x)
print("Second Number is: ", y)
Output:
Enter two values: 7 1
First Number is: 7
Second Number is: 1
An example to take string input from the user.
#multiple inputs in Python using map
x, y = map(str, input("Enter your first and last name ").split())
print("First Name is: ", x)
print("Second Name is: ", y)
d) List Comprehension
List date types also help in taking multiple inputs from the user at a time. The syntax for creating a list and storing the input in it is
x, y = [x for x in input("Enter two value: ").split()]
The list allows you to take multiple inputs of different data type at a time. The below example will help you understand better.
#multiple inputs in Python using list comprehension
x, y = [x for x in input("Enter your name and age: ").split(",")]
print("Your name is: ", x)
print("Your age is: ", y)
Output:
Enter your name and age: FACE Prep, 8
Your name is: FACE Prep
Your age is: 8
Python user input and EOFError Example
n Python 2, raw_input()
returns a string and input()
tries to run the input as a Python expression. So, changing your first line to something like this should work.
n = int(raw_input())
An EOFError is raised when a built-in function like input() or raw_input() do not read any data before encountering the end of their input stream. The file methods like read() return an empty string at the end of the file.
The given code is rewritten as follows to catch the EOFError and find its type.
#eofError.py try: while True: data = raw_input('prompt:') print 'READ:', data except EOFError as e: print e Then if we run the script at the terminal $ echo hello | python eofError.py
OUTPUT
prompt:READ: hello prompt:EOF when reading a line
Python User Input Expressions in Command Line
The user input()
function in Python will evaluate any expression that the user inputs. Here’s are some examples:
>>> input(8/3)
2.6666666666666665
>>> input(800-3)
797
>>> input(len("Python"))
6
>>> input(min([1,2,3]))
1
>>> input(max([1,2,3]))
3
Differences to input() and raw_input()
The usage of input or better the implicit evaluation of the input has often lead to serious programming mistakes in the earlier Python versions, i.e. 2.x Therefore, there the input function behaves like the raw_input function from Python2.
input() function works differently between Python 3 and Python 2. Both the input()
and raw_input()
the function accepts input from the user.
Input and raw_input() in Python 2
- The main difference between those two functions is input() function automatically converts user input to appropriate type. i.e., If a user-entered string input() function converts it into a string, and if a user entered a number it converts to an integer.
- raw_input() convert every user input to string.
raw_input() function of python 2 is renamed to input() in Python 3.x and original input() function is removed from Python 3.
The difference when using these functions only depends on what version of Python is being used. For Python 2, the function raw_input()
is used to get string input from the user via the command line, while the input()
function returns will actually evaluate the input string and try to run it as Python code.
Input and raw_input in Function in Python 3
In Python 3, raw_input()
the function has been deprecated and replaced by the input()
function and is used to obtain a user’s string through the keyboard. And the input()
function of Python 2 is discontinued in version 3. To obtain the same functionality that was provided by Python 2’s input()
function, the statement eval(input())
must be used in Python 3.
Must Read: Best Book to Learn Python in 2020
Conclusion
So, in conclusion, we can say it’s very easy to take the user input in Python from the input() function. Python user input can be taken easily with the help of input() and raw_input() depending on the version of Python you are using.
If you have still any doubts, let me know your comments and feedback in the section below.
Happy Coding!
Hi, I have gone through ur contents,
they are well explained…
But I have one doubt.i.e
In some python ide’s if I use input () ,
It shows EOF error
Could u please tell me the other forms of taking input from the Console(test cases)
This happens usually when the IDE has no support to take real-time input. Online IDEs or IDEs which take input in terms of file throws this error.
Check the settings if there is a fixed input file when running it.
Otherwise try using
echo "1 2" | test.py
way of providing input to python.Regards,
Pratik