Skip to contentSkip to navigation

Module 02 · Lesson 02

Interactive Input & Output

Read what a user types with input(), convert it before doing maths, and format results neatly with f-strings, decimal places, thousands separators and aligned columns.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Ask and answer
  • Fill in with f-strings
  • Round and add commas
  • Line up columns

Talk with the person at the keyboard

Programs ask with `input()` and answer with `print()`. f-strings make the answers neat.

  • Ask

    input("Name? ") shows a question, waits for typing and Enter, then hands back what was typed.

  • Always text

    Whatever is typed arrives as a str, even 42. Use int() or float() before doing maths.

  • f-strings

    Put f before the quotes and names in {} braces: f"Hi {name}" fills in the value.

  • Formatting

    After a colon in the braces: :.2f for 2 decimals, :, for thousands commas, :<8 to line up columns.

Programs that talk

Asking and answering is how most programs meet people.

  • Quiz gamesAsk a question, read the answer, print well done or try again.
  • Cash machinesAsk for an amount, then print a receipt with the money to 2 decimal places.
  • Sign-up screensRead a name and say Welcome, Sam! with an f-string.
  • LeaderboardsNames and scores line up in neat columns, one f-string per row.

Inside an f-string

This line fills two values into one sentence. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

f:The f turns the text into an f-string, so the braces get filled in. Forget it and you see the braces themselves.

Make answers look neat

These examples store what a person would type in a variable, so they run straight away. Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Say hello

typed stands in for what input() would hand back.

Your turn: Change typed to your own name and check both lines.

Python
typed = "Mo"  # what the person typed
print(f"Hello, {typed}!")
print(f"{typed} has {len(typed)} letters")
Output
Press Run to see what it prints.

Watch typed text become a receipt

Press Step to run one line at a time. Line 1 stands in for `input()`.

Ready. Press Step to run the first line.

  1. typed = "3"
  2. boxes = int(typed)
  3. cost = boxes * 1.5
  4. print(f"Boxes: {boxes}")
  5. print(f"Cost: {cost:.2f}")

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Padding with zeros?

print(f"{7:03}")

0 of 6 answered

Common input and output misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Talking with the user

Reading input

The built-in function input() pauses the program, waits for the user to type something and press Enter, and then returns what they typed. The text you pass in is shown as a prompt, so the user knows what to type.

Try it 1: edit me, then Run
name = input("What is your name? ")
print("Nice to meet you,", name)
Output
Press Run to see what it prints.

When this runs, the prompt appears, the program waits, and whatever the user types is stored in name. Leave a space at the end of the prompt so the answer does not touch the question. On this site, the terminal under the editor shows the prompt and lets you type the answer.

input() always gives text

This is the most important rule in the lesson: input() always returns a string, even when the user types digits. If someone types 14, you get "14", two characters of text.

Try it 2: edit me, then Run
age = input("Age: ")          # the user types 14
print(age + 1)                # TypeError: can only concatenate str (not "int") to str
Output
Press Run to see what it prints.

Convert the answer to the type you need, usually straight away, so the rest of the program works with a real number.

Try it 3: edit me, then Run
age = int(input("Age: "))
print("Next year you will be", age + 1)
price = float(input("Price: "))
Output
Press Run to see what it prints.

If the user types something that cannot be converted, such as ten, int() raises ValueError. Handling that politely is covered in a later course; for now, assume the user types what you asked for.

Writing good prompts

A prompt is the only help a user gets, so make it specific. input("Number: ") leaves people guessing; input("How many tickets (1 to 6)? ") tells them the range and the unit. When a program asks several questions, ask them in a sensible order and keep the style the same for each one. After reading the answers, it is good manners to repeat the important ones back, as in You asked for 3 tickets, so a user can spot a typing mistake before anything happens.

Answers often contain stray spaces, especially at the end, because people press the space bar before Enter. The string method .strip() removes spaces from both ends: name = input("Name: ").strip(). You will meet many more string methods in a later lesson; this one is worth using from the start.

Programs also read the same kind of answer more than once. Each call to input() waits for a new line, so three calls read three answers in order. In a later lesson you will put input() inside a loop to keep asking until the user types something valid.

f-strings

Joining text with + and str() works but gets messy quickly. An f-string is a string with the letter f before the opening quote. Inside it, anything in curly braces { } is worked out as Python and its value is put into the text.

Try it 4: edit me, then Run
name = "Ada"
score = 42
print(f"{name} scored {score} points")
print(f"Double: {score * 2}")
Output
Press Run to see what it prints.

This prints Ada scored 42 points and Double: 84. Any expression can go inside the braces: a variable, a calculation or a function call. Numbers are converted to text automatically, so you never need str() inside an f-string. If you forget the f, Python prints the braces and the name literally, {name} scored {score} points, which is an easy mistake to spot once you know it.

Formatting numbers

After the expression, a colon starts a format specification that controls how the value looks.

Try it 5: edit me, then Run
price = 3.5
visitors = 1234567
ratio = 0.256
print(f"{price:.2f}")       # 3.50, two decimal places
print(f"{visitors:,}")      # 1,234,567
print(f"{ratio:.1%}")       # 25.6%
Output
Press Run to see what it prints.

.2f means "a float with 2 digits after the point" and rounds as needed, which is exactly what money needs. , adds thousands separators, and % multiplies by 100 and adds a percent sign. They combine, so {1234.5:,.2f} gives 1,234.50.

Lining up columns

A number right after the colon sets a minimum width. < aligns left, > aligns right and ^ centres. Text aligns left by default and numbers align right.

Try it 6: edit me, then Run
print(f"{'Tea':<8}{2.5:>6.2f}")
print(f"{'Sandwich':<8}{4.25:>6.2f}")
Output
Press Run to see what it prints.

Each item is padded to 8 characters and each price to 6, so the prices line up in a column however long the names are. Inside an f-string written with double quotes, use single quotes for any strings in the braces.

Output you already know

Everything from the first program lesson still applies: print() takes several values, sep sets what goes between them and end sets what goes after. f-strings and these settings work together; use whichever makes the line clearest.

You may also see the older str.format() method, as in "{} has {} letters".format("Python", 6). It uses the same format specifications, but f-strings are shorter and easier to read, so prefer them in new code.

Syntax

The general shape of the statements in this lesson.

syntax.py
answer = input("Question? ")     # always a str
n = int(input("Number: "))       # convert straight away
f"Hello {name}"                  # f-string
f"{x:.2f}"   f"{n:,}"   f"{r:.0%}"   # decimals, separators, percent
f"{text:<10}"  f"{num:>8}"  f"{t:^6}"  # align left, right, centre
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A tip calculator with formatted output

Beginner

Work out a 15% tip on a bill and the total, showing money with two decimal places. In a real program the bill would come from input(); here it is set directly so you can run it.

Python
bill_text = "48.6"          # what input("Bill: ") would return
bill = float(bill_text)
TIP_RATE = 0.15
tip = bill * TIP_RATE
print(f"Bill:  {bill:.2f}")
print(f"Tip:   {tip:.2f}")
print(f"Total: {bill + tip:.2f}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The text is converted with float() because a bill can have pence. The .2f format rounds each amount to two places and always shows both digits, so 48.6 appears as 48.60. Formatting only changes how a number looks, never the value stored in the variable.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Doing maths with the raw input

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
apples = input("Apples: ")
print(apples * 2)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

If the user types 3, this prints 33 instead of 6

Write this instead

apples = int(input("Apples: "))
print(apples * 2)

Why it happens

input() returned the string "3", and * on a string repeats it.

In the real world

Where this shows up in software people use every day.

  1. A parking meter receipt

    Transport

    A car park machine asks how many hours you will stay, then prints a receipt. The program below uses the value a driver might type.

    Why Python fits

    The typed answer is converted to an int, multiplied by the rate, and printed in aligned columns with money to two decimal places, the way a real receipt looks.

    Python
    hours_text = "3"            # what the driver typed
    RATE = 1.8
    hours = int(hours_text)
    cost = hours * RATE
    print(f"{'Hours':<8}{hours:>6}")
    print(f"{'Rate':<8}{RATE:>6.2f}")
    print(f"{'Total':<8}{cost:>6.2f}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why does the Lab not use input()?

Lab checks run your code without anyone at the keyboard, so tasks give the typed answer in a variable instead. The playground and lesson examples let you try input() yourself.

Does :.2f change the number?

No. It only changes how the number is shown. The variable still holds the full value.

Can I put a calculation inside the braces?

Yes, any expression works, for example f"{price * qty:.2f}". Keep it short; long expressions are clearer as their own variable.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/5 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 5 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.