Interactive Programs: User Input
Stop writing static code. Learn how to prompt users for information, capture their keyboard input, and process the data.
Talking to the User
Up until now, our code has run silently without any human interaction. The input() function pauses the program and waits for the user to type something and press Enter.
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")The Catch: Everything is Text
A very common trap for beginners is forgetting that input() always returns a String. Even if the user types the number 42, Python sees it as the text "42". If you try to do math with it, your program will crash.
Solving the Text Trap with Casting
To fix this, we wrap the input function inside int() or float() to convert the text into usable numbers immediately.
# Correct way to get a number
age = int(input("How old are you? "))
if age >= 18:
print("You are eligible to vote.")
else:
years_left = 18 - age
print(f"Sorry, you must wait {years_left} more years.")