Lesson 12 of 18 · 2 min
input() — Getting Information from the User
The WHY — Why input() Exists
Programs need to respond to the person running them. Without input(), your programs would be static — they could only work with values you hard-coded. With input(), your programs become interactive.
The Golden Rule of input()
input() ALWAYS returns a string — no matter what the user types.
Even if the user types 42, Python stores the string "42" (text), NOT the number 42. This causes crashes if you try to do math with it.
name = input("Enter your name: ") # pause program, wait for user to type, then store it
print("Hello,", name) # use what the user typedOutput: Enter your name: Priya Hello, Priya
The Most Common Beginner Crash — and the Fix
# WRONG — this crashes!
age = input("Enter your age: ") # user types 20, Python stores "20" (string)
print(age + 5) # TypeError: cannot add string and integerError: TypeError: can only concatenate str (not "int") to str
# CORRECT — convert input to the right type first
age = int(input("Enter your age: ")) # convert to integer immediately
gpa = float(input("Enter your GPA: ")) # convert to decimal immediately
print(f"In 5 years you will be {age + 5}") # now math works
print(f"Your GPA: {gpa:.2f}") # can format and displayOutput: Enter your age: 20 Enter your GPA: 3.75 In 5 years you will be 25 Your GPA: 3.75
