Python input With Examples

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.

This will output:

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:

Now it will output:

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:

This will output:

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.

This will output:

Python input

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:

That’s all for a quick roundup on python input function and how to get user input in python.

By admin

Leave a Reply

%d bloggers like this: