How to accept input from user in Python’s Built-in Functions in python


The input() Function



Programs usually require input that can come from different sources: keyboard, mouse clicks, database, another computer’s storage, or the internet. Since the keyboard is the most common way to gather input, Python provided its users the input() function. This function has an optional parameter called the prompt string.


Once the input function is called, the prompt string will be displayed on the screen and the program flow stops until the user has entered an input. The input is then interpreted and the input() function returns the user’s input as a string.


To illustrate, here is a sample program that collects keyboard input for name and age:



name = input(“May I know your name? “)

print(“It’s a pleasure to meet you ” + name + “!”)

age = input(“Your age, please? “)

print(“So, you’re ” + age + ” years old, ” + name + “!”)



Before you save the code, take a close look at the string to be printed on the second line. You’ll notice that there is a blank space after ‘you’ and before the double quote. This space ensures that there will be a space between ‘you’ and the ‘name’ input when the print command is executed. The same convention can be seen on the 4th line with the print command where ‘you’re’ is separated by a single space from the ‘age’ input and ‘old’ is separated by a space from the ‘name’ input.


Save the code as info_input.py and run it.



The Python Shell will display the string on the first line:
May I know your name?
A response is needed at this point and the program stops executing until a keyword input is obtained. Let’s type and enter the name Jeff to see what happens:


It’s a pleasure to meet you Jeff!

Your age, please?



The program has now proceeded to the next input function and is waiting for the keyboard input. Let’s enter 22 as Jeff’s age and see what the program does next:


So, you’re 22 years old, Jeff!


The program printed the last string on the program after a keyboard response was obtained. Here is the entire output on the Python Shell:


May I know your name? Jeff

It’s a pleasure to meet you Jeff!

Your age, please? 22

So, you’re 22 years old, Jeff!


Comments