Skip to main content

Asking for User Input

To make your programs interactive, you need a way to ask the user questions. In Python, we use the input() command to do this.

When Python reads the input() command, it pauses the program and waits for the user to type something on their keyboard and press Enter.


1. Asking a Question

You can put a question inside the input() command so the user knows what to type:

user_name = input("Enter your name: ")
print("Welcome to Python,", user_name)

How this runs:

  1. The computer prints Enter your name: and pauses.
  2. The user types their name (e.g., Rahul) and presses Enter.
  3. Python takes that name and stores it in the user_name variable.
  4. Finally, it prints the welcome message.

2. The Golden Rule of input()

Here is a very important rule in Python: The input() command always captures the user's response as Text (a String).

Even if the user types a number like 25, Python sees it as the text "25", not the actual mathematical number 25.

age = input("Enter your age: ")
print(type(age)) # Output: <class 'str'> (which means String/Text)

The Math Mistake (Concatenation Trap)

Because input is captured as text, trying to do math with it will give you a weird result:

# If the user types 10 and 20:
num1 = input("First number: ") # Stores "10" (text)
num2 = input("Second number: ") # Stores "20" (text)

print(num1 + num2) # Output: 1020 (It joins the text together, instead of adding!)

3. Converting Text to Numbers (Type Casting)

If you want to do math with user input, you must convert the captured text into a number. We call this converting or casting data types:

  • int(): Converts text to a whole number.
  • float(): Converts text to a decimal number.

You can wrap the input() command inside these converters directly:

# Convert the user's input to a whole number immediately
user_age = int(input("Enter your age: "))
next_year_age = user_age + 1

print("Next year you will be:", next_year_age)
# Convert the user's input to a decimal number
price = float(input("Enter price: "))
print("Price with tax:", price * 1.1)

What's Next?

Now that we know how to print output and ask for input, let's look at the best way to format our text messages dynamically using f-strings in the next lesson!