Input, Output & Operators
Talk to the user, do maths, and combine text neatly with f-strings.
print() — sending output
You've already met print. It accepts multiple things separated by commas:
print("Score:", 42)
print("x", "y", "z", sep="-")
print("loading", end="...")
print("done")
Score: 42
x-y-z
loading...done
input() — asking the user a question
input() shows a prompt, waits for the user to type something and press Enter,
and returns whatever they typed as a string:
name = input("What's your name? ")
print("Hello,", name)
What's your name? Sam
Hello, Sam
If you want a number, convert it:
age_text = input("How old are you? ")
age = int(age_text)
print("Next year you'll be", age + 1)
Maths operators
print(2 + 3) # 5 — add
print(10 - 4) # 6 — subtract
print(6 * 7) # 42 — multiply
print(9 / 2) # 4.5 — divide (always returns a float)
print(9 // 2) # 4 — integer divide (drops the remainder)
print(9 % 2) # 1 — remainder (modulo)
print(2 ** 10) # 1024 — power (2 to the 10th)
Comparison operators
These return a boolean (True or False):
print(3 == 3) # True — equal to
print(3 != 4) # True — not equal
print(5 > 2) # True
print(5 <= 5) # True
One
= vs two
= assigns a value (x = 3). == compares two values
(x == 3). Mixing them up is a classic beginner bug.
String operators
You can stick strings together with + and repeat them with *:
print("Py" + "thon") # Python
print("ha" * 3) # hahaha
f-strings — the nicest way to combine text and values
Put an f before the opening quote, then put any expression inside { }:
name = "Pat"
score = 87
print(f"{name} scored {score}/100")
print(f"That's {score / 100:.0%}")
Pat scored 87/100
That's 87%
The bit after the : is an optional format spec — useful examples:
{value:.2f}— show 2 decimal places (3.14){value:.0%}— show as a percent with no decimals (87%){value:,}— thousands separators (1,000,000)
A tiny program tying it together
name = input("Your name: ")
price = float(input("Item price: "))
qty = int(input("Quantity: "))
total = price * qty
print(f"Thanks {name} — your total is £{total:.2f}")
Your name: Sam
Item price: 9.99
Quantity: 3
Thanks Sam — your total is £29.97