Lesson 92 +10 XP

User Input

User Input

input() reads a line of text from the user. It always returns a string.

The basics

username = input("Enter username: ")
print("Username is: " + username)

The prompt is printed, then Python waits for the user to type and press Enter.

input() returns a string

Even if the user types a number, you get a string:

age = input("How old are you? ")
print(type(age))  # <class 'str'>

Convert to a number

Use int() or float():

age = int(input("How old are you? "))
print(age + 5)

Handle bad input

If the user types something that isn't a number, int() raises a ValueError. Catch it:

try:
    age = int(input("Age? "))
except ValueError:
    print("That wasn't a number!")

Security note

Never trust raw input. Validate and convert it before using it.

TL;DR

  • input(prompt) reads text from the user.
  • It always returns a string.
  • Convert with int() or float() when you need numbers.
  • Wrap conversions in try/except for safety.