If you are writing command-line Python scripts, then you will need to request input from the user at some point. In Python, the mechanism for requesting command-line values is the input()
function.
Let’s go over how to use input()
and make sure you’re prepared to avoid three common pitfalls.
The input() Function
Fortunately for new Python enthusiasts, the input()
function is straightforward, accepting only one optional argument. The single argument is the text that will be shown on the command-line as the terminal waits for the user’s input. As the user, you can type in your value and submit by pressing ENTER.
input("Enter your name: ")
Now, the code we have above is incomplete because we aren’t storing the user’s value. We can fix that by assigning the return of input()
to a variable.
name = input("What is your name: ")
print(name)
That’s really all there is to using the input()
function. While the function itself is very simple, there is nuance in implementing input()
in a script so that it does not become a liability.
Below are three common pitfalls that new coders fall into. Fortunately for you, we’ll avoid them by reading ahead.
1. Requesting Numeric Input
We asked the user for a text value in our earlier example, but what happens when we need a numeric value?
price = input("Enter the price: ")
total = price * 1.06
print("The total price is", total)
2. User Input Causing Value Errors
Setting a proper data type is only one step to properly implementing user input. Let’s say we want user input but the value that is actually entered causes an error. What do we do?
total = float(input("How much did you pay? "))
units = int(input("How many did you purchase? "))
print("The unit price is", total/units)
Before dismissing the sequence in the screenshot, always remember how easy it is to make a typing mistake. We strive to code in a way that is error-proof.
Use try/except
statements to solve for erroneous values.
try:
total = float(input("How much did you pay? "))
units = int(input("How many did you purchase? "))
print("The unit price is", total/units)
except Exception as e:
print("Error:", e)
A try/except statement will attempt to execute all commands in the try block. If an exception is encountered, then the except block will be executed. Aside from being able to report on the exception, the biggest advantage here is that your script will not stop executing from the error.
3. Continually Requesting User Input
We’ve learned how to convert our user input as well as account for erroneous values. But when we receive a bad input, most likely you’ll want to re-prompt the user.
The input()
function does not have a built-in “retry” mechanism, so we will use a while loop to continually request user input until it is valid. There are many different ways to implement a while loop for continuous user input. We’ll use an infinite while loop with a break statement as a generic solution.
total = float(input("How much did you pay? "))
while True:
try:
units = int(input("How many did you purchase? "))
if(units > 0):
break
else:
print("Invalid input")
except Exception as e:
print("Error:",e)
print("The unit price is", total/units)
In the code example above, we‘ve put all our strategies together. We convert our input to an integer, which is wrapped by a try/except which is wrapped by an infinite while loop.
It is easy to start using the input()
function, but there are many potential traps since user input is always uncertain. However, with the three tips we shared, you’re prepared to venture out into the wild.