>>> Python for Beginners Chapter 05 of 10

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.")
What is your name? Grace Hello, Grace! 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}.")
How old are you? 25 Next year you will be 26.

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}")
--- Simple bill splitter --- Total bill: K1200 How many people? 4 Each person pays K300.0
โœ๏ธ Try it yourself

Write a program that asks for two numbers and prints their sum. Remember to convert both inputs with int() first.

Guard against bad input

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