Chapter 05 ยท Working With Data
Getting Input
So far our programs already knew everything. Real programs ask questions and react to the answers. That's what input() is for.
Asking a question
The input() function shows a prompt and waits for the user to type something. Whatever
they type comes back as a string:
name = input("What is your name? ")
print(f"Hello, {name}! Welcome.")
In the playground, type the answer into the Input box before pressing Run.
Input is always text โ convert when you need numbers
This is the number-one beginner trap. input() gives you text even when the user types
digits, so convert with int() before doing maths:
age_text = input("How old are you? ")
age = int(age_text)
print(f"Next year you will be {age + 1}.")
Leave out the int() and age + 1 would crash, because you can't add 1 to text.
A tiny useful program
print("--- Simple bill splitter ---")
bill = float(input("Total bill: K"))
people = int(input("How many people? "))
each = bill / people
print(f"Each person pays K{each}")
Write a program that asks for two numbers and prints their sum. Remember to convert both inputs with
int() first.
If the user types "twenty" when you call int(), the program crashes. For now, just assume
sensible input โ later you'll learn how to catch mistakes gracefully. Every real app has to handle the
user typing the wrong thing.
Recap
input("prompt")asks the user and returns what they type, as text.- Convert with
int()orfloat()before doing maths. - Combined with variables and maths, you can already build small useful tools.