Getting Input from the User

Learn how to ask the user for information, read what they type, and use it in your program.

~19 min Beginner

input() pauses and waits

Most useful programs talk to the user. They ask questions, read the answers, and do something with them. In Python, the input() function does all of this. It pauses your program, shows a message, waits for the user to type something, and then hands back what they typed.

name = input("What is your name? ")
print(f"Hello, {name}!")

When you run this, the program stops and shows:

What is your name? _

The user types their name and presses Enter. Only then does the program continue and print the greeting. Nothing happens until Enter is pressed.

The text inside the brackets is called the prompt. It is optional, but you should almost always give one. Without it the user sees a blinking cursor and has no idea what to type. Put a space at the end of the prompt so the answer does not touch your question.

name = input("Name: ")      # clear and tidy
name = input("Name:")       # the answer sticks to the colon
name = input()              # no hint at all, confusing

It always returns a string

This is one of the most common beginner mistakes. No matter what the user types, even a number, input() always returns a string.

age = input("How old are you? ")
print(type(age))   # <class 'str'>, it is a string, not a number!

To do math with it, you must convert it first:

age = input("How old are you? ")
age = int(age)        # convert string to integer
next_year = age + 1
print(f"Next year you will be {next_year}.")

You can also do the conversion on the same line, which is cleaner:

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

Read it from the inside out. input(...) runs first and gives text. Then int(...) turns the text into a number. Finally the number is stored in age.

What happens if you forget to convert? Python does not add numbers, it joins text:

a = input("First number: ")    # user types 5
b = input("Second number: ")   # user types 3
print(a + b)                   # 53, not 8!

The two strings "5" and "3" were glued together. This kind of bug is easy to miss, so always check the type of what you read.

int or float?

Here is a small program that takes two numbers and adds them:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
total = num1 + num2
print(f"The sum of {num1} and {num2} is {total}.")

We use float() instead of int() so the user can enter decimal numbers too. Which one should you pick? Ask yourself what the value is.

  • Use int() for whole things you count: age, number of items, a menu choice.
  • Use float() for measured things that can have decimals: price, height, temperature.
  • Use nothing for text: names, cities, answers like yes or no.

float() accepts whole numbers too, so float("3") gives 3.0. But int() rejects decimals, so int("3.5") fails with an error. When you are not sure, float() is the safer choice.

print(int("42"))      # 42
print(float("3.5"))   # 3.5
print(float("7"))     # 7.0
print(int("3.5"))     # ValueError

Handling bad input

What if the user is supposed to enter a number but types a word instead? Python crashes with a ValueError. We can handle this cleanly:

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("That is not a valid number. Please enter a whole number.")

Python tries the code under try. If a ValueError happens, it jumps straight to the except block instead of crashing. If everything works, the except block is skipped.

We will cover try and except in detail in the error handling lesson. For now, just know that this pattern catches bad input and shows a friendly message.

Real programs usually keep asking until the answer is valid. Combine the pattern with a loop (you will learn loops soon):

while True:
    try:
        age = int(input("Enter your age: "))
        break
    except ValueError:
        print("Numbers only, please.")
print(f"Got it: {age}")

The loop repeats forever until break runs, and break only runs when the conversion succeeds.

Putting it together

Here is a complete program that uses everything so far: variables, input, type conversion and f-strings.

print("Welcome to the personal info program!")
print("---")

name = input("Enter your name: ")
age = int(input("Enter your age: "))
city = input("Enter your city: ")

print()
print("Here is your information:")
print(f"  Name: {name}")
print(f"  Age:  {age}")
print(f"  City: {city}")
print(f"  In 10 years you will be {age + 10} years old.")
Note: print() with nothing inside prints a blank line. This is useful for adding spacing to make your output look cleaner and easier to read.

Try running it, then change it. Ask for a favorite color, or work out the birth year with 2026 - age. Changing working code and watching what happens is the fastest way to learn.

Cleaning up what users type

People type in many different ways. Some add extra spaces. Some use capitals. Your program should not fail because of that, so clean the text right after you read it:

answer = input("Continue? (yes/no) ")
answer = answer.strip().lower()

if answer == "yes":
    print("Great, let us continue.")

strip() removes spaces from both ends, and lower() makes everything lowercase. Now " YES ", "Yes" and "yes" all work. You can chain both on the same line, too:

name = input("Name: ").strip().title()   # "  alice smith " becomes "Alice Smith"

Get used to this habit. In real programs, the user is the least predictable part of the system.

Showing output better

print() can do more than show one thing. Give it several values and it puts a space between them:

print("Name:", "Alice", "Age:", 25)   # Name: Alice Age: 25

Two options change how it behaves. sep sets what goes between values, and end sets what goes at the end. Normally the end is a new line.

print("a", "b", "c", sep="-")        # a-b-c
print("Loading", end="...")
print("done")                         # Loading...done

To read several values from one line, combine input, split and a conversion:

x, y = input("Enter two numbers: ").split()   # user types: 3 4
print(int(x) + int(y))                         # 7

That works because split() cuts the text into a list, and Python can put the two pieces into x and y.

Key takeaways

  • input("prompt") pauses the program, shows the prompt and returns what the user typed
  • The result is always a string, even if it looks like a number
  • Convert with int() for whole numbers and float() for decimals
  • int(input(...)) does both steps in one line
  • try and except ValueError stop bad input from crashing your program
  • strip() and lower() clean up messy answers
  • print() with nothing inside prints a blank line
Sign up to track your progress Mark lessons as read and pick up where you left off Sign up free to unlock this practice Your first practice lesson is free to try. Create an account to unlock the rest and save your progress