User Input
So far, every program has worked with values written into the code. Real programs respond to the people using them. The input() function lets your program ask a question and wait for an answer.
Asking a question
input() shows a prompt, waits for the user to type something and press Enter, then gives back what they typed.
Run this and type your answer in the Output panel:
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")Tip: End your prompt with a space, as in
"What is your name? ", so the user's answer doesn't run into the question.
Input is always a string
Whatever the user types, input() returns a string, even if it looks like a number. Run this and type 5:
answer = input("Type a number: ")
print(type(answer))
print(answer * 3)You got 555, not 15, because "5" * 3 repeats the text. To do maths, convert the input first:
answer = input("Type a number: ")
number = int(answer)
print(number * 3)You can convert in one step by wrapping input() in int() or float():
age = int(input("How old are you? "))
height = float(input("How tall are you in metres? "))
print(f"Next year you will be {age + 1}.")
print(f"That's {height * 100:.0f} cm.")Use int() for whole numbers and float() when the user might type a decimal.
When the input isn't a number
If the user types something that can't be converted, Python raises a ValueError. Run this and type hello:
number = int(input("Type a whole number: "))
print(number * 2)You'll learn how to handle errors like this gracefully in the Errors and Exceptions lesson. For now, just know why it happens.
Going deeper: Why int("3.5") fails optional
int() can turn a decimal number into a whole number, but it can't turn decimal text into one. The text "3.5" isn't a whole number, so int() refuses:
print(int(3.5)) # a float: works, gives 3
print(int("3.5")) # text with a decimal point: ValueErrorIf the user might type a decimal but you need a whole number, convert to float first, then to int:
answer = input("How many hours did you work? ")
hours = int(float(answer))
print(f"Full hours: {hours}")Remember that int() cuts off the decimals rather than rounding. Use round(float(answer)) if you want 3.7 to become 4.
Cleaning up text input
People add stray spaces and capital letters. Combine input() with the string methods from the last lesson to tidy things up:
color = input("What's your favourite colour? ").strip().lower()
print(f"You chose: {color}")Going deeper: Reading several values from one line optional
split() from the String Methods lesson lets you read several values the user types on one line. Run this and type something like 3 4:
line = input("Enter width and height separated by a space: ")
parts = line.split()
width = int(parts[0])
height = int(parts[1])
print(f"Area: {width * height}")Putting it together: a tip calculator
bill = float(input("Bill amount: "))
tip_percent = int(input("Tip percentage (e.g. 15): "))
people = int(input("Number of people: "))
tip = bill * tip_percent / 100
total = bill + tip
each = total / people
print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Each person pays: {each:.2f}")Exercises
These exercises are interactive. Your program asks questions, and you type the answers in the Output panel.
Exercise 1: Personal greeting
Ask the user for their name and their city, then print Hello <name> from <city>!
# Ask for name and city, then greet the user
Call input() twice and store each answer in its own variable.
Print with an f-string: f"Hello {name} from {city}!".
Exercise 2: Add two numbers
Ask for two whole numbers and print their sum. If the user types 4 and 6, it should print 4 + 6 = 10.
# Ask for two numbers and print their sum
input() always gives back text. Wrap it in int(...) to get a number.
Print with f"{a} + {b} = {a + b}".
Exercise 3: Temperature converter
Ask for a temperature in Celsius (it may have decimals) and print it in Fahrenheit using F = C × 9 / 5 + 32. For 25, print 25.0°C is 77.0°F.
# Convert Celsius to Fahrenheit
Use float(input(...)), because the temperature might have decimals.
Calculate celsius * 9 / 5 + 32, then print both values in an f-string.
Exercise 4: Fix the program
This program is meant to tell the user how old they'll be in 10 years, but it crashes. Run it, read the error, and fix it.
age = input("How old are you? ")
print(f"In 10 years you will be {age + 10}.")Read the error: Python can't add text and a number.
Convert the answer to a number with int(...) as soon as you read it.
Summary
input("prompt ")waits for the user and returns what they typed.- The result is always a string. Convert it with
int()orfloat()before doing maths. - Converting text that isn't a number raises a
ValueError. - Chain
.strip()and.lower()to clean up text input. split()lets you read several values from one line.