Python input() is a builtin function used to read a string from standard input. The standard input in most cases would be your keyboard.
Syntax – input()
Following is the syntax of input() function.
x = input(prompt)
where prompt is a string, that is printed to the standard output, before input() function starts reading the value input by user. prompt is helpful in letting the users know what kind of input the application is expecting, something like a clue. Prompt is optional though.
input() function returns the string keyed in by user in the standard input.
Indetail Working of input()
So, when you call this input() function, Python Interpreter waits for user input from the standard input. When user enters a value in the console input, using keyboard, each character is echoed to the output. This helps user as a feedback of what value is being input. After you enter the value and hit Return or Enter key, the string that is keyed in by you until this last enter key, is returned by the input() function.
Example 1: Python input() Function
In this example, we shall read a string from user using input() function.
x = input('Enter a value : ') print('You entered : ', x)
Example 2: Read Number using Python input()
By default, input() function returns a string. If you would like to read a number from user, you can typecast the string to int, float or complex, using int(), float() and complex() functions respectively.
In the following program, we shall read input from user and convert them to integer, float and complex.
x = int(input('Enter an integer : ')) print('You entered : ', x) x = float(input('Enter a float : ')) print('You entered : ', x)
Example 3: Python input() – without prompt message
Prompt string is an optional argument to input() function.
In this example, let us not provide a string argument to input() and read a string from user.
x = input() print('You entered : ', x)
In this tutorial of Python Examples, we learned how to read input or string from user via system standard input.