Reading User Input in Python
Learning to take user input is one of the paths you need to master a programming language. Almost all programs are now interactive. They need data from the user to provide the desired output. In this tutorial, we will discuss reading user input in Python.
Python offers a myriad of built-in functions that are accessible at the Python prompt. Moreover, two built-in functions read input from the keyboard. They are:
- input ( prompt )
- raw_input ( prompt )
input ()
The input()
function asks the user for input and processes the expressions. This means that the Python interpreter automatically identifies the data type of the user input. A user can enter an int, float, string, list, or even a tuple. If the input is not supported, then Python will return a syntax error.
Some characteristics of the input()
function are:
input()
is a blocking function. A blocking function temporarily halts the program flow until the function is executed successfully or relieved. As long as you haven’t entered an input,input()
will block your code, and your program won’t proceed.- The text display on the output that asks the user to enter a value is optional. If left blank, the input should display a blinking cursor instead.
raw_input()
The raw_input()
function also asks the user for input but takes precisely what is typed from the keyboard and converts them to string.
Since Python 3 doesn’t include the raw input function anymore, the main difference between the two only matters with Python 2. As mentioned before, input()
automatically detects and converts to the appropriate data type of the user input. On the other hand, raw_input()
converts everything to string.
You can use typecasting to convert your raw input to its original data type forcefully. For instance, if you want to have an integer instead, you can use int(raw_input())
.
Password Program Using input() and raw_input()
For our example, we will write a program in Python that asks the user for password input. If the password is wrong, it prints “Password incorrect. Try again.” to the terminal. Otherwise, if it’s correct, it prints “Password correct. You are now logged in!” and exits the program.
Sample Code in Python 3
password = ''
while password != 'strongestPASSWORD123!': password = input("Enter Password: ") if password == 'strongestPASSWORD123!': print("Password is correct. You are now logged in!") else: print("Password Incorrect. Try again.")
Sample Code in Python 2
password = ''
while password != 'strongestPASSWORD123!': password = raw_input("Enter Password: ") if password == 'strongestPASSWORD123!': print("Password is correct. You are now logged in!") else: print("Password Incorrect.")