Session 3 - Input & Output

Session 3 of the Python Fundamentals series, covered in depth. It makes the program listen with input() and talk back with print(). The central rule is that input() ALWAYS returns a string, so doing math on it requires int() or float() first. The session covers the prompt, the string trap, conversion with int() and float() and the ValueError it can raise, and building output with str() and f-strings, including {value:.2f} formatting, then works several read-compute-print programs. The snippets were verified under CPython 3.12, with input shown as the value the user types.

Subject: Python Fundamentals · 98 slides · code lesson

Open the interactive version of this deck · Homework for this lesson

What this lesson covers

The lesson, slide by slide

1. Input & Output

Title

Python Fundamentals - Session 3

Ask a question, listen to the answer, talk back

2. What you will be able to do

Objectives

So far the program only talks. Now it will listen - and this is where programs start to feel interactive. By the end you can:

  1. Use input() to ask the user a question and store their answer.
  2. Explain why input() always hands you text - even for digits.
  3. Convert with int() / float() so you can do math, and read a ValueError.
  1. Turn numbers into text with str().
  2. Build clean output with f-strings, including {value:.2f} for money.
  3. Write a full read-compute-print program.

3. What survived from Session 2 - Variables & Types?

Warm-up

Discussion prompt

Before we open Session 3 - Input & Output: without looking back, what was the main idea of Session 2 - Variables & Types, and what could you do by the end of it that you could not do before?

Hint: One sentence for the idea, one for the skill. If the second one is blank, that is the part to revisit.

Answer:

That session covers assignment and reassignment, the four core types, the type() function, and why "100" is not the number 100.

4. Asking with input()

Section

Part 1

5. input() asks a question

Concept

input("...") shows your message, then pauses and waits for the user to type and press Enter.

Whatever they typed is handed back to your program, so you store it in a variable.

prompt — The message inside input("...") that tells the user what to type. It is shown on screen, then the program waits for an answer.

6. Break it if you can: input() asks a question

Counterexample

Discussion prompt

input("...") shows your message, then pauses and waits for the user to type and press Enter.

That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.

Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.

Answer:

Whatever they typed is handed back to your program, so you store it in a variable.

7. Store the answer in a variable

Concept

The answer is only useful if you keep it: name = input("Your name? ").

Read it right-to-left like any assignment: run the input, get the answer, then attach the name to it.

8. By analogy: Store the answer in a variable

Analogy

Discussion prompt

Explain Store the answer in a variable by analogy to something with no Python Fundamentals in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.

Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.

Answer:

The answer is only useful if you keep it: name = input("Your name? ").

9. A simple greeter

Worked example

The user runs this and types Sam:

name = input("What's your name? ")
print("Welcome,", name)

Line 1 shows the prompt and waits

Why: input pauses; whatever the user types becomes the value of name.

Line 2 uses that value

Why: Verified by execution: with Sam typed, prints Welcome, Sam.

user typesname becomesprints
Sam"Sam"Welcome, Sam

10. Draw the shape of it: A simple greeter

Blank canvas

Draw it

Draw what A simple greeter just did — the shape of it, not the line-by-line working. One picture, labels only where you need them. Then check it against the steps: anything you could not draw is a step you followed rather than understood.

11. The prompt is just a string

Concept

The text inside input("...") is an ordinary string - end it with a space so the user's typing does not touch your question.

input("Age? ") reads nicer than input("Age?") because of that trailing space.

12. Teach it back: The prompt is just a string

Explain it

Discussion prompt

Explain The prompt is just a string to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.

Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.

Answer:

The text inside input("...") is an ordinary string - end it with a space so the user's typing does not touch your question.

13. input() ALWAYS returns text

Concept

This is the one rule that trips up every beginner: input() gives back a str - always.

Even if the user types 12, you get the text "12", not the number 12. You can print it, but you cannot do math on it yet.

14. The keyboard only knows characters

Intuition

Think about what a keyboard sends: individual characters. Press 1 then 2 and the program receives the two characters "12" - text that happens to look like a number.

Python will not guess whether you wanted a number. It hands you the text and leaves the choice to you: need it as a number? then convert it.

15. Predict the next row: Proof: it is a str

Pattern

Predict first

The table runs: 12 | "12" | str · hello | "hello" | str

In Proof: it is a str, given the rows so far: what is the next one — the row where user types is 3.5?

Correct: 3.5 | "3.5" | str

user typesage becomestype(age)
12"12"str
hello"hello"str
3.5"3.5"str

Why: The relationship between the columns, not the individual numbers, is what generates the next row. Digits, words, decimals - all arrive as a str.

16. Proof: it is a str

Worked example

The user types 12:

age = input("How old are you? ")
print(type(age))

Whatever is typed comes back as text

Why: Digits, words, decimals - all arrive as a str.

type() confirms it every time

Why: Verified by execution: <class 'str'>.

user typesage becomestype(age)
12"12"str
hello"hello"str
3.5"3.5"str

17. Fill in: type(age) for Proof: it is a str

Comparison

Comparison matrix

From Proof: it is a str: refill the type(age) column from what you know. The rest of the table is as it appeared.

user typesage becomestype(age)
12"12"str
hello"hello"str
3.5"3.5"str

18. Something is wrong here: doing math on raw input

Anomaly

Predict first

A student writes this, and it looks reasonable:

Adding to input() directly. The user types 5.

It is wrong. Say what breaks — and say it before you turn the page.

Correct: input() returned a string. Adding the number 1 to text stops the program.

Wrap the input in int() to get a real number.

Why: input() returned a string. Adding the number 1 to text stops the program.

19. Trap: doing math on raw input

Trap

The trap

Adding to input() directly. The user types 5.

age = input("Age? ")
print(age + 1)

age is the TEXT "5", so age + 1 mixes a str and an int

Why: input() returned a string. Adding the number 1 to text stops the program.

expressionresult
"5" + 1TypeError: can only concatenate str (not "int") to str

The fix

Wrap the input in int() to get a real number.

age = int(input("Age? "))
print(age + 1)

int(input(...)) converts the text to a number

Why: With 5 typed, int("5") is 5, and 5 + 1 is 6. Real output: 6.

user typesage becomesage + 1
55 (int)6

20. Converting the Answer

Section

Part 2

21. int(input(...)) for whole numbers

Concept

Wrap input() in int() when you need a whole number: age = int(input("Age? ")).

The input() runs first and returns text; int() then turns that text into a number - all in one line.

22. What has to happen first: Next year's age

Ranking

Put in order

Put the moves of Next year's age into the order they have to happen.

  1. Line 1: int() wraps the input, so age is a number
  2. Line 2: now the math works
  3. Trace each value

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. input() returns "12"; int("12") makes it 12.

23. Next year's age

Worked example

The user types 12:

age = int(input("How old are you? "))
next_year = age + 1
print("Next year you will be", next_year)

Line 1: int() wraps the input, so age is a number

Why: input() returns "12"; int("12") makes it 12.

Line 2: now the math works

Why: 12 + 1 is 13.

Trace each value

Why: Verified by execution: prints Next year you will be 13.

linevariablevaluetype
1age12int
2next_year13int
3(printed)Next year you will be 13-

24. What each one costs: Next year's age

Trade off

Comparison matrix

From Next year's age: every row here is a choice with a cost. Fill the type column, then say which row you would actually pick and what you give up for it.

linevariablevaluetype
1age12int
2next_year13int
3(printed)Next year you will be 13-

25. float(input(...)) for decimals

Concept

Use float() instead when the answer can have a decimal point: a price, a temperature, a measurement.

float("3.5") is 3.5; float("4") is 4.0. It accepts whole-number text too.

26. Doubling a price

Worked example

The user types 4.5:

price = float(input("Price? "))
print(price * 2)

float() reads the decimal text

Why: float("4.5") is 4.5 - a number you can multiply.

The math runs

Why: Verified by execution: 4.5 * 2 is 9.0 (a float stays a float).

user typespriceprice * 2
4.54.59.0

27. int() or float()?

Concept

Use int() when the value is naturally whole - a count, an age, a score. Use float() when a decimal is possible - money, averages, measurements.

One catch: int() rejects decimal text like "3.5". If the input might have a dot, reach for float().

28. Something is wrong here: int() on decimal text

Anomaly

Predict first

A student writes this, and it looks reasonable:

Using int() on text that has a decimal point. The user types 3.5.

It is wrong. Say what breaks — and say it before you turn the page.

Correct: "3.5" has a decimal point, which int() refuses.

Use float() for anything that might have a decimal.

Why: "3.5" has a decimal point, which int() refuses. The program stops with a ValueError.

29. Trap: int() on decimal text

Trap

The trap

Using int() on text that has a decimal point. The user types 3.5.

n = int(input("A number: "))

int() only parses whole-number text

Why: "3.5" has a decimal point, which int() refuses. The program stops with a ValueError.

inputresult
3.5ValueError: invalid literal for int() with base 10: '3.5'

The fix

Use float() for anything that might have a decimal.

n = float(input("A number: "))

float() accepts decimals (and whole numbers too)

Why: float("3.5") is 3.5, and float("4") is 4.0. Real outcome: no error, n is a float.

inputfloat(...)
3.53.5
44.0

30. Break it on purpose: int() on decimal text

Break the constraint

Discussion prompt

The rule this trap just fixed:

Use float() for anything that might have a decimal.

Now break it on purpose. Build a case that violates it and follow the consequences until something visibly fails. Where does the failure first show up — and would you have noticed it if you had not been looking?

Hint: The dangerous rules are the ones whose violation still produces an answer. If yours fails loudly, try to find one that fails quietly.

Answer:

"3.5" has a decimal point, which int() refuses. The program stops with a ValueError.

31. What a ValueError means

Concept

ValueError means the value was the wrong kind for the operation - here, text that is not a valid number.

int("hello") fails the same way: there is no number to read. Session 12 shows how to catch this so a typo does not crash the program.

32. When conversion cannot work

Worked example

print(int("hello"))

There is no number inside "hello"

Why: int() has nothing valid to convert, so it raises a ValueError and stops.

expressionresult
int("hello")ValueError: invalid literal for int() with base 10: 'hello'

The lesson

Why: Only convert text that really is a number. We will guard against bad input later with try / except.

33. Why is this step legal: Then compute and show

Explain it to yourself

Discussion prompt

In Two inputs: rectangle area this move is made:

Then compute and show

Why is that legal? Name the rule or definition it rests on before you read on.

Hint: If you can only say "because that is what you do", the rule is the thing to go and find.

Answer:

Verified by execution: 12 * 8 is 96, prints Area: 96.

34. Two inputs: rectangle area

Worked example

The user types 12, then 8:

length = int(input("Length? "))
width = int(input("Width? "))
print("Area:", length * width)

Each input is read and converted in turn

Why: length becomes 12, width becomes 8 - both ints.

Then compute and show

Why: Verified by execution: 12 * 8 is 96, prints Area: 96.

variablevalue
length12
width8
area96

35. Inspect it line by line: Two inputs: rectangle area

Error analysis

Annotate

Walk the callouts on Two inputs: rectangle area. Each one is a place this is easy to get subtly wrong.

  • length becomes 12, width becomes 8 - both ints.
  • Verified by execution: 12 * 8 is 96, prints Area: 96.

36. Average of two scores

Worked example

The user types 7, then 3:

a = int(input("First: "))
b = int(input("Second: "))
print("Average:", (a + b) / 2)

Read both numbers first

Why: a is 7, b is 3.

Average uses / , so the result is a float

Why: Verified by execution: (7 + 3) / 2 is 5.0. Note the parentheses - without them, precedence would divide only b by 2.

expressionvalue
a + b10
(a + b) / 25.0

37. Building Output

Section

Part 3

38. str(): number to text

Concept

str() goes the other direction: str(100) is the text "100". You need it to join a number into a message with +.

39. Joining with str()

Worked example

score = 100
print("Score: " + str(score))

str(score) makes "100", then + joins

Why: Both sides of + are now text, so they glue into "Score: 100".

Read the output

Why: Verified by execution: Score: 100.

stepvalue
str(score)"100"
"Score: " + str(score)"Score: 100"

40. Something is wrong here: forgetting str() with +

Anomaly

Predict first

A student writes this, and it looks reasonable:

Joining a number onto text with + but no str().

It is wrong. Say what breaks — and say it before you turn the page.

Correct: "Score: " is a str and score is an int.

Convert with str() - or just use a comma, or an f-string.

Why: "Score: " is a str and score is an int. Python stops rather than guess.

41. Trap: forgetting str() with +

Trap

The trap

Joining a number onto text with + but no str().

score = 100
print("Score: " + score)

+ cannot join text and a number

Why: "Score: " is a str and score is an int. Python stops rather than guess.

expressionresult
"Score: " + 100TypeError: can only concatenate str (not "int") to str

The fix

Convert with str() - or just use a comma, or an f-string.

score = 100
print("Score:", score)
print(f"Score: {score}")

Three easy fixes

Why: A comma lets print mix types; an f-string drops the value in; str(score) makes it joinable. Real output: Score: 100 (twice).

fixoutput
commaScore: 100
f-stringScore: 100

42. Which of these survive contact with Session 3 - Input & Output?

Two truths and a lie

Sort into buckets

Some of these hold up and some are the exact mistakes this lesson is built to prevent. Sort them.

Holds up
input("...") shows your message, then pauses and waits for the user to type and press Enter.; The answer is only useful if you keep it: name = input("Your name? ").; The text inside input("...") is an ordinary string - end it with a space so the user's typing does not touch your question.
Breaks
Adding to input() directly. The user types 5.; Using int() on text that has a decimal point. The user types 3.5.
sound
These are stated as this lesson states them — each one survives the edge cases Session 3 - Input & Output puts it through.
flawed
Each of these is lifted from a trap in this deck: reasonable-sounding, and wrong in a way that only shows up once you rely on it.

43. f-strings: fill in the blanks

Concept

Put an f before the quotes and wrap each value in { }. Python drops the value straight into the text - no +, no str().

f"Score: {score}" is the clean, modern way to build a message.

44. Where does each piece belong: Session 3 - Input & Output

Sorting

Sort into buckets

These are the pieces of Session 3 - Input & Output, out of order. Put each one back under the part of the lesson it belongs to.

Asking with input()
input() asks a question; Store the answer in a variable; A simple greeter
Converting the Answer
int(input(...)) for whole numbers; Next year's age; float(input(...)) for decimals
Building Output
str(): number to text; Joining with str(); f-strings: fill in the blanks
s1
Asking with input() is where Session 3 - Input & Output puts input() asks a question, Store the answer in a variable, A simple greeter. Knowing which part of the lesson a problem belongs to is most of knowing which method to reach for.
s2
Converting the Answer is where Session 3 - Input & Output puts int(input(...)) for whole numbers, Next year's age, float(input(...)) for decimals. Knowing which part of the lesson a problem belongs to is most of knowing which method to reach for.
s3
Building Output is where Session 3 - Input & Output puts str(): number to text, Joining with str(), f-strings: fill in the blanks. Knowing which part of the lesson a problem belongs to is most of knowing which method to reach for.

45. The braces are blanks to fill

Intuition

Read an f-string like a fill-in-the-blank sentence. Everything outside { } is printed as-is; each { } is a blank that Python fills with that value's text.

It converts numbers to text automatically, so you never mix up str and int inside it.

46. Restore the missing line: An f-string in action

Fill the middle

Fill in the blanks

From An f-string in action — one line has had its right-hand side removed. Put it back.

name = "Sam"
badges = 3
print(f"___ has ___ badges")

Why: name is what everything below it consumes, so the wrong expression here fails later and somewhere else. {name} becomes Sam, {badges} becomes 3 - converted for you.

47. An f-string in action

Worked example

name = "Sam"
badges = 3
print(f"{name} has {badges} badges")

Each {...} is replaced by that value's text

Why: {name} becomes Sam, {badges} becomes 3 - converted for you.

Read the output

Why: Verified by execution: Sam has 3 badges.

piecefills with
{name}Sam
{badges}3
whole f-stringSam has 3 badges

48. f-strings can do math inside {}

Concept

The braces can hold an expression, not just a variable: f"{c * 9/5 + 32}" computes then inserts the result.

It keeps the calculation right where it is shown - readable and compact.

49. Temperature converter

Worked example

The user types 100:

c = int(input("Temp in C? "))
print(f"{c}C is {c * 9/5 + 32}F")

Line 1: read and convert the temperature

Why: c is the number 100.

Line 2: the second blank computes the formula

Why: Verified by execution: 100 * 9/5 + 32 is 212.0, so it prints 100C is 212.0F.

blankfills with
{c}100
{c * 9/5 + 32}212.0

50. Formatting: {value:.2f}

Concept

Add :.2f inside the braces to show a number with exactly two decimal places - perfect for money.

f"${price:.2f}" turns 4.5 into $4.50, and 3.14159 into 3.14.

51. Two decimal places

Worked example

print(f"{3.14159:.2f}")
print(f"${4.5:.2f}")

:.2f rounds to two decimals for display

Why: 3.14159 shows as 3.14; 4.5 shows as 4.50 (padded to two places).

Read the output

Why: Verified by execution. This only changes how it looks, not the stored value.

expressionshows
{3.14159:.2f}3.14
${4.5:.2f}$4.50

52. Fill in: shows for Two decimal places

Comparison

Comparison matrix

From Two decimal places: refill the shows column from what you know. The rest of the table is as it appeared.

expressionshows
{3.14159:.2f}3.14
${4.5:.2f}$4.50

53. Text Answers & Converting Later

Section

Part 4

54. Not everything needs converting

Concept

Only convert when you need to do math. A name, a color, a yes/no answer - leave those as the text input() gives you.

Converting a name with int() would just crash. Match the conversion to what you actually do with the value.

55. Why is this step legal: Drop it into a message

Explain it to yourself

Discussion prompt

In Echoing a text answer this move is made:

Drop it into a message

Why is that legal? Name the rule or definition it rests on before you read on.

Hint: If you can only say "because that is what you do", the rule is the thing to go and find.

Answer:

Verified by execution: with Alex typed, prints Alex is a great choice!

56. Echoing a text answer

Worked example

The user types Alex:

color = input("Favorite color? ")
print(f"{color} is a great choice!")

No conversion - color stays text

Why: We only display it, so the str from input() is exactly what we want.

Drop it into a message

Why: Verified by execution: with Alex typed, prints Alex is a great choice!

user typescolorprints
Alex"Alex"Alex is a great choice!

57. input() with no prompt

Concept

You can call input() with empty parentheses - it just waits with no message shown. Usually you print a question on the line before.

58. Prompt on its own line

Worked example

The user types yes:

print("Ready to start?")
answer = input()
print("You said:", answer)

The print asks, the bare input() waits

Why: input() with nothing inside still returns whatever is typed.

Echo the answer

Why: Verified by execution: with yes typed, prints You said: yes.

user typesanswerprints
yes"yes"You said: yes

59. You can convert in a separate step

Concept

int(input(...)) does it in one line, but you can also read first and convert after: raw = input(...) then age = int(raw).

Two steps can be clearer when you want to check or clean the text before converting.

60. Plan first: Read, then convert

Step zero

Discussion prompt

Read, then convert — before any calculation: what is the plan? Name the moves in order, in plain English, without doing the arithmetic.

Hint: It starts with: Line 1: raw is the text "25"

Answer:

  1. Line 1: raw is the text "25"
  2. Line 2: convert it to a number
  3. Line 3: the math runs

61. Read, then convert

Worked example

The user types 25:

raw = input("Age? ")
age = int(raw)
print(age + 1)

Line 1: raw is the text "25"

Why: Straight from input(), still a str.

Line 2: convert it to a number

Why: int(raw) makes 25. Now math is allowed.

Line 3: the math runs

Why: Verified by execution: 25 + 1 is 26.

variablevaluetype
raw"25"str
age25int

62. Convert at the boundary

Intuition

Think of conversion as happening at the door: text comes in from the keyboard, and you turn it into a number the moment it enters.

After that, the rest of your program works with clean numbers and never worries about the string again.

63. Overwriting the same name is fine

Concept

You can reuse the variable when converting: age = int(age). The right side runs first (text -> number), then the label moves to the number.

After this line, age is a number - the text version is gone, which is usually exactly what you want.

64. Teach it back: Overwriting the same name is fine

Explain it

Discussion prompt

Explain Overwriting the same name is fine to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.

Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.

Answer:

You can reuse the variable when converting: age = int(age). The right side runs first (text -> number), then the label moves to the number.

65. Restore the missing line: Convert onto the same name

Fill the middle

Fill in the blanks

From Convert onto the same name — one line has had its right-hand side removed. Put it back.

age = input("Age? ")
age = int(age)
print(type(age))

Why: age is what everything below it consumes, so the wrong expression here fails later and somewhere else. Verified by execution: type is now <class 'int'>.

66. Convert onto the same name

Worked example

The user types 7:

age = input("Age? ")
age = int(age)
print(type(age))

Line 1: age starts as text

Why: age is "7".

Line 2: int(age) replaces it with a number

Why: Verified by execution: type is now <class 'int'>.

after lineagetype
1"7"str
27int

67. Draw the shape of it: Convert onto the same name

Blank canvas

Draw it

Draw what Convert onto the same name just did — the shape of it, not the line-by-line working. One picture, labels only where you need them. Then check it against the steps: anything you could not draw is a step you followed rather than understood.

68. Mixing a text and a number answer

Concept

A program often reads some text answers and some numeric ones. Keep the text as-is and convert only the numbers.

An f-string then combines them in one clean message.

69. By analogy: Mixing a text and a number answer

Analogy

Discussion prompt

Explain Mixing a text and a number answer by analogy to something with no Python Fundamentals in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.

Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.

Answer:

A program often reads some text answers and some numeric ones. Keep the text as-is and convert only the numbers.

70. Restore the missing line: Name plus score

Fill the middle

Fill in the blanks

From Name plus score — one line has had its right-hand side removed. Put it back.

name = input("Name: ")
score = int(input("Score: "))
print(f"Hi ___, you scored ___ - ___ to go!")

Why: name is what everything below it consumes, so the wrong expression here fails later and somewhere else. name is "Alex"; score is 90 so we can subtract with it.

71. Name plus score

Worked example

The user types Alex, then 90:

name = input("Name: ")
score = int(input("Score: "))
print(f"Hi {name}, you scored {score} - {100 - score} to go!")

name stays text; score is converted

Why: name is "Alex"; score is 90 so we can subtract with it.

One f-string combines both, plus a computed value

Why: Verified by execution: Hi Alex, you scored 90 - 10 to go!

blankfills with
{name}Alex
{score}90
{100 - score}10

72. Watch it run: Name plus score

Pattern

Step through it

Step through Name plus score one row at a time. What is driving the change, and what would the row after the last one be?

  1. Step 1: blank is {name}
  2. Step 2: blank is {score}
  3. Step 3: blank is {100 - score}

73. Putting It Together

Section

Part 5

74. Read all, then compute, then print

Concept

A tidy program has three phases: gather the inputs, compute the results, then show the output.

Keeping them in that order makes programs easy to read and to debug.

75. Break it if you can: Read all, then compute, then print

Counterexample

Discussion prompt

A tidy program has three phases: gather the inputs, compute the results, then show the output.

That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.

Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.

Answer:

Keeping them in that order makes programs easy to read and to debug.

76. What has to happen first: Build it: a trainer profile

Ranking

Put in order

Put the moves of Build it: a trainer profile into the order they have to happen.

  1. Gather: one text input, one number input
  2. Compute: badges remaining
  3. Show: one f-string ties it together

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. Verified by execution: Sam has 3 badges, 5 to go.

77. Build it: a trainer profile

Worked example

The user types Sam, then 3:

name = input("Name: ")
badges = int(input("Badges: "))
left = 8 - badges
print(f"{name} has {badges} badges, {left} to go")

Gather: one text input, one number input

Why: name is "Sam", badges is 3 (converted).

Compute: badges remaining

Why: 8 - 3 is 5, stored in left.

Show: one f-string ties it together

Why: Verified by execution: Sam has 3 badges, 5 to go.

variablevalue
name"Sam"
badges3
left5

78. Watch it run: Build it: a trainer profile

Pattern

Step through it

Step through Build it: a trainer profile one row at a time. What is driving the change, and what would the row after the last one be?

  1. Step 1: variable is name
  2. Step 2: variable is badges
  3. Step 3: variable is left

79. What has to happen first: Build it: a tip calculator

Ranking

Put in order

Put the moves of Build it: a tip calculator into the order they have to happen.

  1. Read the bill as a float
  2. Compute tip and total
  3. Show with money formatting

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. Money can have decimals, so float() is the right choice.

80. Build it: a tip calculator

Worked example

The user types 40 for the bill:

bill = float(input("Bill: "))
tip = bill * 0.2
total = bill + tip
print(f"Tip: ${tip:.2f}  Total: ${total:.2f}")

Read the bill as a float

Why: Money can have decimals, so float() is the right choice. bill is 40.0.

Compute tip and total

Why: tip is 40.0 * 0.2 = 8.0; total is 48.0.

Show with money formatting

Why: Verified by execution: Tip: $8.00 Total: $48.00.

variablevalueshown as
tip8.0$8.00
total48.0$48.00

81. Inspect it line by line: Build it: a tip calculator

Error analysis

Annotate

Walk the callouts on Build it: a tip calculator. Each one is a place this is easy to get subtly wrong.

  • Money can have decimals, so float() is the right choice. bill is 40.0.
  • Verified by execution: Tip: $8.00 Total: $48.00.

82. Predict the next row: Build it: a two-number adder

Pattern

Predict first

The table runs: {a} | 20 · {b} | 22

In Build it: a two-number adder, given the rows so far: what is the next one — the row where blank is {a + b}?

Correct: {a + b} | 42

blankfills with
{a}20
{b}22
{a + b}42

Why: The relationship between the columns, not the individual numbers, is what generates the next row. a is 20, b is 22. Without int(), the next line would join text instead of add.

83. Build it: a two-number adder

Worked example

The user types 20, then 22:

a = int(input("First: "))
b = int(input("Second: "))
print(f"{a} + {b} = {a + b}")

Convert both inputs to int

Why: a is 20, b is 22. Without int(), the next line would join text instead of add.

The f-string shows the sum

Why: Verified by execution: 20 + 22 = 42.

blankfills with
{a}20
{b}22
{a + b}42

84. What each one costs: Build it: a two-number adder

Trade off

Comparison matrix

From Build it: a two-number adder: every row here is a choice with a cost. Fill the fills with column, then say which row you would actually pick and what you give up for it.

blankfills with
{a}20
{b}22
{a + b}42

85. The read-and-respond recipe

Pattern

1. Ask with input() and store the answer

Why: answer = input("..."). The program pauses until Enter.

2. Need a number? Wrap it in int() or float()

Why: int() for whole values, float() for possible decimals. Skip this and any math is a TypeError.

3. Compute the results

Why: Do the arithmetic on the converted numbers, storing what you need.

4. Respond with an f-string

Why: f"{a} + {b} = {a + b}" drops values (and even expressions) straight into the message. Use :.2f for money.

86. Choosing the right conversion

Pattern

Whole count (age, score, badges) -> int()

Why: int(input(...)). Rejects decimal text, so only use it when a dot is impossible.

Possible decimal (money, temp, average) -> float()

Why: float(input(...)). Accepts both "3.5" and "4".

Just displaying it -> leave it as text

Why: A name or a yes/no answer needs no conversion at all.

87. Where this shows up: Session 3 - Input & Output

Real world

Discussion prompt

Outside this lesson: where does Session 3 - Input & Output actually turn up? Name one concrete situation — a job, a piece of software someone ships, a decision somebody has to make — and say which part of Choosing the right conversion is doing the work in it.

Hint: Vague is the failure mode here. "Engineering" is not a situation; "deciding whether this build is fast enough to ship" is.

Answer:

Session 3 of the Python Fundamentals series, in depth. Making the program listen with input() and talk back with print().

88. Check Yourself

Section

Part 5

89. Check: what type is it?

Check

The user types 20.

score = input("Score? ")
print(type(score))
user typestype(score)
20?

Check your understanding

What does type(score) print?

  • A. <class 'int'>
  • B. <class 'str'> (correct)
  • C. <class 'float'>
  • D. <class 'input'>

Answer: B

Why: input() always returns a str, even for digits. score is the text "20", so type(score) is <class 'str'>. Verified by execution.

Why A tempts people
input() never returns an int on its own; only int(input(...)) does.
Why C tempts people
Typing 20 gives the text "20", not 20.0.
Why D tempts people
There is no 'input' type - input() hands back an ordinary str.

90. Check: the math trap

Check

The user types 4.

n = input("A number: ")
print(n + 2)
nn + 2
"4"?

Check your understanding

What happens?

  • A. It prints 6
  • B. It prints 42
  • C. TypeError: can only concatenate str (not "int") to str (correct)
  • D. It prints 4

Answer: C

Why: n is the text "4" because input() returns a str. Adding the number 2 mixes a str and an int, so Python stops. int(input(...)) would make it print 6. Verified by execution.

Why A tempts people
6 needs conversion: int(n) + 2. As written, n is text, so the addition never runs.
Why B tempts people
Joining would give "42" only if both sides were strings, like n + "2". Here 2 is a number.
Why D tempts people
It does not silently print n - it errors before printing.

91. Check: fix with conversion

Check

The user types 4. Which line makes it print 6?

n = int(input("A number: "))
print(n + 2)
nn + 2
4 (int)?

Check your understanding

Now what prints?

  • A. 6 (correct)
  • B. 42
  • C. TypeError
  • D. 4

Answer: A

Why: int(input(...)) converts "4" to the number 4, so 4 + 2 is 6. Wrapping input in int() is exactly what enables the math. Verified by execution.

Why B tempts people
"42" is string joining. Here n is an int, so + adds instead of joins.
Why C tempts people
No type mismatch now - both sides are numbers, so no error.
Why D tempts people
The + 2 runs, so it prints 6, not the original 4.

92. Check: int() on a decimal

Check

The user types 2.5.

x = int(input("Value: "))
inputresult
2.5?

Check your understanding

What happens?

  • A. x becomes 2
  • B. x becomes 3
  • C. ValueError: invalid literal for int() with base 10: '2.5' (correct)
  • D. x becomes 2.5

Answer: C

Why: int() only parses whole-number text. "2.5" has a decimal point, so int() refuses and raises a ValueError. Use float() for decimals. Verified by execution.

Why A tempts people
int() does not truncate text - it rejects it. int(2.5) on a float would give 2, but this is text.
Why B tempts people
int() neither rounds nor accepts "2.5" as text - it errors.
Why D tempts people
int() cannot return a decimal. To keep 2.5 you would use float().

93. Check: f-string blanks

Check

What fills the braces?

a = 6
b = 4
print(f"{a} and {b} make {a + b}")
blankfills with
{a}?
{a + b}?

Check your understanding

What does this print?

  • A. 6 and 4 make 10 (correct)
  • B. {a} and {b} make {a + b}
  • C. 6 and 4 make 64
  • D. a and b make a + b

Answer: A

Why: The f before the quote makes each {...} a blank filled with that value's text: 6, 4, and the computed 6 + 4 = 10. Verified by execution.

Why B tempts people
That is what prints WITHOUT the f. The f is what turns the braces into blanks.
Why C tempts people
{a + b} computes the sum (10), it does not glue 6 and 4 into 64.
Why D tempts people
The braces are replaced by the variables' values, not their names.

94. Fill in: fills with for Check: f-string blanks

Comparison

Comparison matrix

From Check: f-string blanks: refill the fills with column from what you know. The rest of the table is as it appeared.

blankfills with
{a}?
{a + b}?

95. Check: money formatting

Check

What does :.2f do here?

price = 5
print(f"${price:.2f}")
valueshown as
5?

Check your understanding

What does this print?

  • A. $5.00 (correct)
  • B. $5
  • C. $5.0
  • D. $5.2f

Answer: A

Why: :.2f formats the number with exactly two decimal places, so 5 shows as 5.00. The value is unchanged - only its display. Verified by execution.

Why B tempts people
Without :.2f you would get $5, but the format spec forces two decimals.
Why C tempts people
:.2f means two decimal places, not one, so it is 5.00 not 5.0.
Why D tempts people
The :.2f is a format instruction, not literal text - it never appears in the output.

96. Check: which conversion?

Check

You are reading a bill amount that could be $19.99.

bill = ____(input("Bill? "))
needsso use
decimals allowed?

Check your understanding

What should fill the blank?

  • A. float (correct)
  • B. int
  • C. str
  • D. nothing - leave it as input()

Answer: A

Why: A bill like 19.99 has a decimal point, so float() is the right converter. int() would raise a ValueError on "19.99". Verified by reasoning about int()'s decimal restriction.

Why B tempts people
int() rejects decimal text like "19.99" with a ValueError, so it cannot read a price with cents.
Why C tempts people
str() keeps it as text, so you could not do math (like adding tax) on it.
Why D tempts people
Leaving it as input() gives text; any arithmetic on it would be a TypeError.

97. Connect it up: Session 3 - Input & Output

Connect it up

Draw it

One page, no notation unless you need it: draw how these connect — Asking with input() · Converting the Answer · Building Output · Text Answers & Converting Later · Putting It Together · Check Yourself. Put an arrow wherever one of them is what makes another possible, and label the arrow with why.

98. What you can do now

Recap

input() asks and returns the answer as text. To do math, convert with int() or float(). Respond with an f-string.

You writeYou get
input("Age? ")text, e.g. "12"
int(input("Age? "))a number, e.g. 12
float(input("Bill? "))a decimal, e.g. 19.99
f"{a} + {b} = {a + b}"drops values and math into text
f"${x:.2f}"two decimal places for money

The program can now listen and reply. Next session it learns to decide - to do different things based on the answer, with if / elif / else.

Sources

  1. Python 3 Library Reference - Built-in Functions (input, print, int, float, str)
  2. Python 3 Reference - Formatted string literals (f-strings)
  3. All snippets and error messages executed under CPython 3.12; input shown as the typed value. — Author verification run, 2026-07-15 (Python Fundamentals series, Session 3).

Want this taught 1-on-1? Alexander tutors Python Fundamentals — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108