Taking input from a user is often required during the execution of a python program, so here’s a short guide on how to do so.
Python gives us the Built in Function input()
as a quick and easy way to take input from the user. Calling this function gives the user the opportunity to enter on screen his input. The user’s input is then converted to a string and returned to the python program.
Syntax:
The input() function takes a single parameter, the user input. The returned object is always a string.
Note: Python 2.7 uses raw_input()
instead of input()
.
value = input("Please enter a value: ")
Handling Python Input:
First thing to know is that the input()
function always returns a string. Any numerical value given to it will be converted to a string automatically. So if you wanted to have the User input a number for you to use in some arithmetic calculations, you’ll have to convert it to integer or float first.
num1 = input("Please enter a number 1: ")
num1 = int(num1) # Converts value to integer, and assigns it to itself.
num2 = input("Please enter a number 2: ")
num2 = int(num2)
print(num1 + num2)
Tip: You can save lines by doing this instead
num1 = int(input("Please enter a number: "))
Handling Multiple Inputs:
In some applications, you may wish to take input from the user multiples times. If for instance, you had to take input from the user 100 times, instead of writing out the input line 100 times you would write just one, and put it in a loop. Example shown below. (If you don’t know how this loop works, don’t worry, just know that it will repeat 100 times. Learn more here)
for x in range(100):
value = input("Please enter a number: ")
print(value)
Tip: Make sure to add a semi colon and leave a space in the string within the input() function. It looks much better when displayed on screen.
Keep in mind that once the input prompt appears on screen, your program will essentially “freeze” and resume only when input is received.
Further more, the input prompt will only appear on the command prompt, or the IDE’s shell. If you’re developing a GUI application and need to take input from the User, there are better ways of doing so. For instance, using the MessageBox library will generate an actual prompt on screen with space for user input.
If you are looking for a more advanced way of taking input through the console, check out “Python stdin“. It offers finer control and several built in functions which can take input in various ways.
This marks the end of our, Python User input Tutorial. Use this link to head back to the main Python built-in Functions page. Any suggestions or contributions for CodersLegacy are more than welcome. Let us know what you thought in the comments section below.