User Input

Acadestine

What is User Input?

So far, every script you have written has been a one-way street: you write the data into the code, hit run, and Python displays it. But real software is interactive it listens to what humans have to say, responds to their choices, and adapts in real-time.

To make your programs interactive, Python provides a built-in function called input().

When Python hits the input() function, it does something brand-new: it pauses execution and waits. It prints a prompt message to the terminal and sits there patiently until the user types something on their keyboard and hits the Enter key.

Let's see how it works in code:

Console

        

Here is the correct way to write an input prompt:

Console

        

The Golden Rule of input(): Always a String

There is a critical trap that almost every beginner falls into when they first use input(). You must memorize this rule:

No matter what the user types into the terminal even if they type a pure number like 25 or 3.14 Python will ALWAYS store it as a String (str).

Look at what happens if you try to treat user input as a number without converting it first:

Console

        

Boom! Python crashes with a TypeError: TypeError: can only concatenate str (not "int") to str

Even though the user typed digits, Python wrapped them in invisible quotation marks behind the scenes. Because it is a string ("20"), Python cannot perform math on it until you explicitly cast it using int() or float()!

Combining input() with Type Conversion

Now that you know input() always returns a string, how do you collect numbers from a user without crashing your program?

You combine type casting and input() on the very same line! By wrapping the input() function inside int() or float(), you tell Python to collect the text and immediately transform it into a math number.

Look at how professional developers collect numeric data safely:

Console

        

When Python runs this line, it evaluates from the inside out: 1. It displays the prompt and waits for the user to type a number. 2. It takes that text (e.g., "20") and passes it into int(). 3. It stores the resulting integer (20) inside the user_age variable!

Lesson Summary

You have unlocked interactive programming! Let's review what you learned:

  • input() function: Pauses your program, displays a prompt in the terminal, and waits for the user to type a response and press Enter.
  • The Golden Rule: input() always returns data as a String (str), no matter what characters the user types.
  • Instant Casting: To collect numbers or booleans from users, wrap your input() call directly inside conversion functions like int(input(...)) or float(input(...)).

Your programs can finally listen to real people, accept dynamic data, and calculate custom responses on the fly!

Previous Next Lesson