In this tutorial we will learn about the most common function input()
that we use frequently to take keyboard input from the user from the console. In our many tutorial we have used this, today we will see python input function more closely.
Python input()
Python input function is present in the python builtins.py
. It reads a string from standard input and the trailing newline is stripped.
When the input()
statement is executed then the program get paused until user gives the input and hit the enter key.
input()
returns the string that is given as user input without the trailing newline.
Python get user input
Let’s have a look at a simple example to get user input using python input function.
1 2 3 4 5 6 7 8 |
# taking an input from the keyboard a = input() # taking another input from the keyboard b = input() c = a + b print("a + b = %s + %s = %s" % ( a, b, c )) |
This will output:
1 2 3 4 5 |
45 12 a + b = 45 + 12 = 4512 |
Oops! What is the output? Addition of 45 and 12 is 4512 ?? It’s because the input() method returns String that is given from the keyboard input. To do what we really wanted to, we have to type cast it to integer as following:
1 2 3 |
c = int(a) + int(b) |
Now it will output:
1 2 3 4 5 |
45 12 a + b = 45 + 12 = 57 |
So, after taking input, cast it as the way you want it.
Python input function with String message
In the above example we don’t get any hint what we should do. To give users about the instructions, we can take input as following:
1 2 3 4 5 6 |
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 )) |
This will output:
1 2 3 4 5 |
Please Enter the first number = 45 Enter the second number = 12 Summation of a + b = 45 + 12 = 57 |
Another simple Python user input example
The following example take the name of the user and finds out the number of occurrance of vowels in it.
1 2 3 4 5 6 7 8 9 10 11 12 |
# taking input from prompt name =input("what is your name? ') print('Hello %s' % name) # taking a counter to count the vowels count = 0 for i in name: i = i.capitalize() if i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U': count = count + 1 print('Your name contains %s vowels' % count) |
This will output:
Another thing that I should mention about the python input
function is that it raises an error if the user hits EOF ( for *nix: Ctrl-D, Windows: Ctrl-Z+Return). The raised error is EOFError
. In the above example if you press Ctrl-D then you will see the output as:
1 2 3 4 5 6 7 |
what is your name? ^D Traceback (most recent call last): File "D:/T_Code/PythonPackage3/Input.py", line 2, in name =input('what is your name? ') EOFError: EOF when reading a line |
That’s all for a quick roundup on python input function and how to get user input in python.