What is the input() function?
It's simple: input()
pauses your script, waits for the user to type something, and then hit Enter. Whatever they type gets captured so you can use it.
You can put a message inside the parentheses to tell the user what you want. This is called a prompt.
name = input("Enter your name: ")
print("Hello, " + name)
The program will display "Enter your name: ", wait, and once you type your name and press Enter, it will store it in the name
variable.
The Single Most Important Thing to Remember
input()
ALWAYS gives you a string.
Always.
If the user types 5
, you don't get the number 5
. You get the string '5'
. If they type 3.14
, you get the string '3.14'
. This is the source of many beginner errors.
Why? Because what the user types is just a sequence of characters from the keyboard. Python doesn't assume you want a number.
How to Use It for Numbers
Since you get a string, you can't do math with it directly.
age_string = input("Enter your age: ")
# age_in_ten_years = age_string + 10 # This will CRASH
This fails because you can't add a string (age_string
) and an integer (10
).
You have to convert the string to a number. This is called type casting. Use int()
for integers and float()
for numbers with decimals.
age_string = input("Enter your age: ")
age_number = int(age_string)
age_in_ten_years = age_number + 10
print(age_in_ten_years)
Most people combine the two lines:
age = int(input("Enter your age: "))
This line now does two things: gets the user input, and immediately tries to convert it to an integer.
What If the User Types "ten" instead of 10?
If you try to run int("ten")
, your program will crash with a ValueError.
For now, just know that your code assumes the user will enter valid numbers. Later, you'll learn about try-except blocks to handle these errors without crashing.
Common Mistakes
- Forgetting to cast: Trying to do math with the raw string output from
input()
. Remember,'5' + '5'
is'55'
, not10
. - Bad variable names: Never name your variable
input
. It overwrites the built-in function and will break your code.
# BAD CODE
input = input("Enter something: ") # You just broke the input() function
- Calling input() multiple times: If you need to check the user's input multiple times, store it in a variable first. Don't call
input()
again.
# BAD CODE - Asks for name twice
if input("Name? ") == "admin":
print("Welcome")
elif input("Name? ") == "guest":
print("Hello guest")
# GOOD CODE - Asks once, stores the value
name = input("Name? ")
if name == "admin":
print("Welcome")
elif name == "guest":
print("Hello guest")