Tutorials / Python Basics / Lesson 6

Getting User Input

What You Will Learn

So far your programs have used fixed values. In this lesson, you will learn how to ask the user for information and respond to it.


The input() Function

input() pauses your program and waits for the user to type something and press Enter:

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

Example interaction:

What is your name? Alice
Hello, Alice!

The string inside input() is the prompt — the message shown to the user. The value the user types is returned and stored in the variable.


input() Always Returns a String

This is an important detail. Even if the user types a number, input() returns it as a string:

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

Expected output:

<class 'str'>

If you need to do math with the value, convert it first:

age = int(input("How old are you? "))
print(f"In 10 years you will be {age + 10}.")

Example interaction:

How old are you? 25
In 10 years you will be 35.

Converting Input

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

height = float(input("Your height in metres: "))
weight = float(input("Your weight in kg: "))

bmi = weight / (height ** 2)
print(f"Your BMI is {bmi:.1f}")

Example interaction:

Your height in metres: 1.75
Your weight in kg: 70
Your BMI is 22.9

A Simple Interactive Program

Put it all together:

print("=== Simple Calculator ===")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print(f"{num1} + {num2} = {num1 + num2}")
print(f"{num1} - {num2} = {num1 - num2}")
print(f"{num1} * {num2} = {num1 * num2}")

if num2 != 0:
    print(f"{num1} / {num2} = {num1 / num2:.2f}")
else:
    print("Cannot divide by zero")

Example interaction:

=== Simple Calculator ===
Enter first number: 10
Enter second number: 3
10.0 + 3.0 = 13.0
10.0 - 3.0 = 7.0
10.0 * 3.0 = 30.0
10.0 / 3.0 = 3.33

Handling Bad Input

What if the user types text when you expect a number? The program will crash:

age = int(input("Age: "))  # crashes if user types "hello"

You will learn how to handle this properly when we cover error handling. For now, assume users type the correct type of value.


What You Learned

  • input() pauses the program and waits for user input
  • It always returns a string
  • Use int() or float() to convert the input to a number
  • You can use the input value anywhere in your program

In the next lesson, you will learn how to make decisions in your programs using if statements.