Skip to content
beginner

User Input in Python

A program that never asks a question can only ever do the same thing. The moment you add input(), your script stops being a fixed script and becomes a tool…

Published 2026-05-11Updated 2026-09-158 min read
Beautiful silhouette of mountains and trees at sunrise with vibrant sky colors.
Beautiful silhouette of mountains and trees at sunrise with vibrant sky colors. Photo by taakill on Pexels.

A program that never asks a question can only ever do the same thing. The moment you add input(), your script stops being a fixed script and becomes a tool that reacts to whoever runs it.

In this tutorial, you'll learn how to get python user input with the input() function, store the answer, convert it when you need a number, and handle the mistakes that trip up beginners.

Why User Input Matters

Think about the programs you use every day. A calculator needs the numbers you type. A login form needs your email. A game needs your commands. None of them would be useful if they ignored you.

User input is how a running program gets information from a real person. It lets your code:

  • Ask questions and act on the answers
  • Personalize messages, like greeting someone by name
  • Collect data, such as ages, choices, or measurements

Before you can build anything interactive, you need this one skill. Let's see how small the first step is.

The input() Function

Python's built-in input() function is the simplest way to get user input. When your program calls it, three things happen:

  1. Your program pauses and waits.
  2. The user types a response and presses Enter.
  3. The program continues, using whatever the user typed.

The most basic call looks like this:

input()

That works, but it gives the user no idea what to type. You can pass a prompt—a message shown before the input—inside the parentheses:

input("What is your name? ")

When this runs, Python displays the prompt and waits for the answer.

Tip: Always include a prompt. A blank input() makes your program look frozen, and the user has no idea what you're asking for.

Knowledge check

Check your understanding

Answer this question before you continue.

What is the purpose of passing a message such as "What is your name? " to input()?
Single Choice

Focus: Identify how a prompt changes the behavior of input().

Storing and Using the Input

Calling input() by itself throws the answer away. To do anything with it, store it in a variable:

name = input("What is your name? ")
print("Hello, " + name + "!")

When you run this, you'll see something like:

What is your name? Sarah
Hello, Sarah!

The prompt appears, the program waits, and once Sarah presses Enter, the greeting prints with her name.

If variables are still unfamiliar, review the basic idea first—storing input is just assigning a value to a name.

Knowledge check

Check your understanding

Answer this question before you continue.

If the user types `Mina`, what greeting does this program print after the prompt?
Output Prediction

Focus: Predict the output produced when input is stored and combined with a greeting.

name = input("What is your name? ")
print("Hello, " + name + "!")

The Input Is Always a String

Here's the fact that causes the most beginner confusion: input() always returns a string, even when the user types a number.

If you ask for an age and try to do math with it directly, you'll hit an error:

age = input("How old are you? ")
print(age + 1)  # TypeError: can only concatenate str (not "int") to str

Because age is text like "20", not the number 20, Python refuses to add an integer to it.

To do math, convert the string to a number first:

age = input("How old are you? ")
age = int(age)
print("Next year, you will be " + str(age + 1) + " years old.")

If the user types 20, the program prints Next year, you will be 21 years old.

Use these converters depending on what you need:

  • int() turns input into a whole number.
  • float() turns input into a decimal number.
height = input("Enter your height in meters: ")
height = float(height)
print("You are " + str(height) + " meters tall.")

Common mistake: Forgetting to convert before doing math. The error message is your clue—read it, convert the value, and rerun.

Knowledge check

Check your understanding

Answer this question before you continue.

A user types `20` for this code. Why must the value be converted before adding 1?
Misconception Check

Focus: Distinguish text returned by input() from numeric values used in arithmetic.

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

Taking Multiple Inputs at Once

Sometimes you want several values on one line. The split() method divides a string into parts, and you can unpack them into separate variables.

To see what split() actually returns, inspect it first:

numbers = input("Enter two numbers separated by a space: ")
print(numbers.split())

If the user types 3 7, the program prints:

Enter two numbers separated by a space: 3 7
['3', '7']

The result is a list of two text pieces. Unpacking assigns the first piece to num1 and the second to num2, and then int() turns each text piece into a number:

numbers = input("Enter two numbers separated by a space: ")
num1, num2 = numbers.split()
num1 = int(num1)
num2 = int(num2)
print("The sum is:", num1 + num2)

If the user types 3 7, the program prints The sum is: 10.

split() breaks the string on spaces by default, so each word or number becomes its own piece. This is a handy shortcut when you want a compact input format.

Build a Small Calculator

Now combine what you've learned into one complete task: ask for two numbers on one line, separated by a space, and print their sum, difference, and product.

numbers = input("Enter two numbers separated by a space: ")
num1, num2 = numbers.split()
num1 = int(num1)
num2 = int(num2)
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)

If the user types 3 7, the program prints:

Enter two numbers separated by a space: 3 7
Sum: 10
Difference: -4
Product: 21

This is the same ask-store-convert pattern you've used all along, just applied to two values at once. That pattern is the input boundary behind larger command-line tools and automation scripts: they collect text, convert it where a number is needed, and act on the result.

Knowledge check

Check your understanding

Answer this question before you continue.

If the user enters `8 3`, what three result lines does this calculator print?
Output Prediction

Focus: Calculate the displayed results of a two-number input program after conversion.

numbers = input("Enter two numbers separated by a space: ")
num1, num2 = numbers.split()
num1 = int(num1)
num2 = int(num2)
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)

When the User Types the Wrong Thing

Here's the boundary most tutorials skip: converting is safe only when the user actually types a number. Ask for an age and type abc, and int() raises a ValueError, stopping the program.

For a real user, that's a dead end. The fix is a small retry loop: keep asking until the input converts cleanly.

while True:
    age = input("How old are you? ")
    try:
        age = int(age)
        break
    except ValueError:
        print("That's not a number. Try again.")

If the user types 20, the loop converts it and moves on. If they type abc, it prints a message and asks again.

Note: This pattern is for expected bad input—the user typing letters where a number belongs. It is not a full error-handling lesson. It just keeps a small interactive program from dying on a foreseeable mistake.

The Rule That Ties It Together

A flowchart starts with user input arriving as text, then branches to plain text used as-is or numeric text sent through conversion. Successful conversion leads to using the number; failed conversion loops back to ask again.
Treat every response as text first, then convert numeric input at the boundary and retry invalid entries.

Everything in this tutorial reduces to one decision rule: collect input as text, convert it at the boundary when the program needs a number, and retry when conversion can fail.

  • Plain text, like a name or a favorite color? Store it and use it as-is.
  • A number you'll do math with? Convert it with int() or float() right after you collect it.
  • Input a real person could get wrong? Wrap the conversion in a retry loop so the program asks again instead of crashing.

That single rule is what separates a script that works for you from a tool that survives being handed to someone else.

Practice: Build a Validated Calculator

Put the rule to work. Your task: take the calculator from earlier and make it refuse bad input.

The goal is to keep asking for each number until the user enters something that converts cleanly, then print the sum. Write it yourself before you read on.

Here's one working version:

def get_number(prompt):
    while True:
        value = input(prompt)
        try:
            return int(value)
        except ValueError:
            print("That's not a number. Try again.")

num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
print("The sum is:", num1 + num2)

If the user types abc for the first number, the program asks again instead of dying. Once both numbers convert, it prints the sum.

Experiment on Your Own

  • Change the validated calculator to use float() so it accepts decimals.
  • Ask for a name and a number, then print a personalized message using both.
  • Apply a string method like .lower() to the input before printing it.

Next Steps

You now have the core of interactive programs: ask, store, convert, and use. The rule that ties it together is simple—collect input as text, convert it at the boundary when the program needs a number, and retry when the user can reasonably provide the wrong shape of input.

The natural next move is to finish the validated calculator above, then extend it to handle decimals with float(). That pairs what you just learned with the arithmetic you'll use constantly as you build real programs. When you're ready to shape that raw input into cleaner output, practice formatting and manipulating the values you collect.

Knowledge check

Final check

Finish the article by checking the ideas you just learned.

What change makes this code ask again instead of stopping when the user types `abc`?
Question 1 of 2Debugging

Focus: Use a retry loop to handle nonnumeric input without ending the program.

age = input("How old are you? ")
age = int(age)
print(age)
Which workflow best follows the article's rule for an input that should be a number?
Question 2 of 2Single Choice

Focus: Apply the article's rule for collecting, converting, and retrying user input.

References

  1. Python input()www.programiz.com
  2. Reading User Input From the Keyboard With Python (Overview) (Video) – Real Pythonrealpython.com
Practical resource

Want a more structured Python path?

Use the Python Starter Pack to turn scattered tutorials into a focused practice path.

View the bundle
Coming soon

Python Starter Pack

A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.

$9
PDF BundleTopic PackPythonBeginner
  • 5 curated chapters
  • Enhanced PDF edition with bundle-only learning guidance
  • Offline-friendly format for focused review
  • Source article links for future online updates

Coming soon

Free Python bundle

Get the LearnPyFast Python for Artificial Intelligence Starter Bundle

Build a Python foundation you can actually use. The Python for Artificial Intelligence Starter Pack brings together a guided path through setup, core programming concepts, data structures, files, JSON, APIs, debugging, and practical projects—so you can move quickly from running your first program to understanding and building useful software.

You’ll receive the bundle by email. You can unsubscribe anytime.

No spam. You can unsubscribe anytime. See our Privacy policy.

Related sites

Continue beyond Python

Explore related Worldmonger sites when you want to move from Python basics into JavaScript or LLM application building.

JavaScript tutorialstutorial

LearnJSFast

Beginner-friendly JavaScript tutorials for practical web development and self-taught developers.

JavaScriptFrontendWeb development
Visit LearnJSFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related tutorials

Continue with nearby Python topics and beginner-friendly explanations.

Close-up view of HTML and CSS code displayed on a computer screen, ideal for programming and technology themes.
beginner
11 min read

Basic Math in Python

Python does not make you memorize a calculator manual. It hands you a small set of operators and lets you run the calculation and read the answer…

Read tutorial
Close-up of a large pot filled with black dye used in traditional incense stick production indoors.
beginner
9 min read

Python Comments and Code Style

Comments are not for Python. They are for the next human who reads your code—and that human is often you, six weeks later. The interpreter skips every line…

Read tutorial