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. Useint()orfloat()before doing maths.f-strings
Put
fbefore the quotes and names in{}braces:f"Hi {name}"fills in the value.Formatting
After a colon in the braces:
:.2ffor 2 decimals,:,for thousands commas,:<8to 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
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.
typed = "Mo" # what the person typed
print(f"Hello, {typed}!")
print(f"{typed} has {len(typed)} letters")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.
- typed = "3"
- boxes = int(typed)
- cost = boxes * 1.5
- print(f"Boxes: {boxes}")
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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, centrePress 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
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.
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}")Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
apples = input("Apples: ")
print(apples * 2)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Transport
A parking meter receipt
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.
Pythonhours_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}")OutputPress 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()?
Does :.2f change the number?
Can I put a calculation inside the braces?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.