5. Input & Output & Formatting

Input & Output & Formatting

Programs become interactive when they can talk to the user. In this chapter you will read what someone types, convert it to the right type, and control exactly how your output looks.

Reading input with input()

The input() function pauses your program, shows an optional prompt, waits for the user to type something and press Enter, then hands back what they typed as a string:

PYTHON
name = input("What is your name? ")
print("Hello, " + name + "!")
▸ OUTPUT (user typed Ada)
What is your name? Ada
Hello, Ada!

Converting input to numbers

Because input() always returns a string, you must convert it before doing arithmetic. Use int() for whole numbers and float() for decimals. Forgetting this is one of the most common beginner mistakes:

PYTHON
age_text = input("Your age? ")
age = int(age_text)
print(f"In ten years you will be {age + 10}.")
▸ OUTPUT (user typed 25)
Your age? 25
In ten years you will be 35.

If we had skipped int(), then age + 10 would have tried to add the number 10 to a string and raised a TypeError. You can also combine the two calls on one line: age = int(input("Your age? ")).

Controlling print() with sep and end

The print() function can take several values separated by commas. By default it joins them with a space and adds a newline at the end. Two keyword arguments change that behaviour:

  • sep sets what goes between the values.
  • end sets what goes after the last value instead of a newline.
PYTHON
print("2024", "10", "21", sep="-")
print("Loading", end="...")
print("done")
▸ OUTPUT
2024-10-21
Loading...done

Because the second print ended with "..." instead of a newline, the word "done" appeared on the same line.

Formatting numbers with f-strings

f-strings can also format values. After the expression, add a colon and a format specification. This is invaluable for money, percentages, and tidy tables:

PYTHON
price = 3.5
print(f"Total: ${price:.2f}")

ratio = 0.846
print(f"Score: {ratio:.1%}")

n = 42
print(f"[{n:5}]")
print(f"[{n:<5}]")
▸ OUTPUT
Total: $3.50
Score: 84.6%
[   42]
[42   ]

Here .2f means "a float with two decimal places," .1% means "a percentage with one decimal place" (it multiplies by 100 and adds the sign), and the number 5 sets a minimum width so values line up in columns. The < aligns to the left.

A small interactive program

Putting it together, here is a program that asks for two numbers and reports their sum neatly:

PYTHON
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"{a} + {b} = {a + b:.2f}")
▸ OUTPUT (user typed 2 and 3)
First number: 2
Second number: 3
2.0 + 3.0 = 5.00

You now have the tools to build friendly, interactive programs. Always remember the golden rule of input: convert the string to the number type you need before calculating with it.