Getting User Input

Programs become more useful when they respond to user input. Instead of hardcoding values, you can ask users for information and work with whatever they provide. Python's input() function makes this straightforward.

Basic Input

The input() function pauses your program and waits for the user to type something:

name = input("Enter your name: ")
print("Hello,", name)

The text inside input() is the prompt – it tells users what to enter. The program waits until they press Enter, then continues.

Input Always Returns a String

Here's a crucial detail: input() always returns a string, even when users type numbers:

age = input("Enter your age: ")
print(type(age))    # <class 'str'>

If someone types 25, you get the string "25", not the number 25. This matters when you try to do math:

age = input("Enter your age: ")
next_year = age + 1    # Error! Can't add string and integer

Converting Input to Numbers

To use input as a number, convert it with int() or float():

age_text = input("Enter your age: ")
age = int(age_text)
print("Next year you'll be", age + 1)

You can combine these steps:

age = int(input("Enter your age: "))
print("Next year you'll be", age + 1)

Use int() for whole numbers and float() for decimals:

price = float(input("Enter the price: "))
tax = price * 0.08
print("Tax:", tax)

What Happens With Bad Input?

If users enter something that can't be converted, Python raises an error:

age = int(input("Enter your age: "))
# User types "twenty-five"
# ValueError: invalid literal for int()

You'll learn to handle these situations gracefully when you study error handling. For now, just be aware that conversion can fail.

Building Interactive Programs

With input(), you can create simple interactive tools:

first = input("Enter first number: ")
second = input("Enter second number: ")

total = int(first) + int(second)
print("Sum:", total)

This pattern – get input, process it, show output – is the foundation of countless programs.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion