1.2.14 · D3Introduction to Programming (Python)

Worked examples — Input with `input()` — always returns string, conversion needed

2,451 words11 min readBack to topic

The scenario matrix

Before any code, let's list every distinct situation the same line int(input(...)) or float(input(...)) can land in. Think of this as the full map — each worked example below fills exactly one cell.

Cell User types Converter What happens
A — clean whole number 42 int() works → 42
B — clean decimal 3.14 float() works → 3.14
C — negative sign -7 int() works → -7 (sign kept)
D — surrounding spaces 9 int() works → 9 (spaces trimmed)
E — zero / degenerate 0 or empty int() 0 works; empty crashes
F — decimal into int() 3.5 int() crashes (ValueError)
G — letters (garbage) twenty int() crashes (ValueError)
H — forgot to convert 3 then 4 none + joins → "34" (wrong)
I — word problem mixed float/int real calculation
J — exam twist tricky mix you decide reason it out

The three big axes here are: (1) which converter matches the meaning (whole vs decimal), (2) sign and whitespace (does the text survive cleaning?), and (3) does the text even look like a number at all (or does it crash?). The picture below shows those three axes as a decision funnel.

Figure — Input with `input()` — always returns string, conversion needed

Now let's fill every cell.


Case A — the clean whole number


Case B — the clean decimal


Case C — the negative sign survives


Case D — spaces around the number


Case E — zero and the degenerate empty input

This cell has two sub-cases because "nothing typed" is the true edge of the map.


Case F — a decimal fed to int()

Look at the picture below — it shows the two-hop route str → float → int that survives a decimal, versus the direct str → int road that hits a wall.

Figure — Input with `input()` — always returns string, conversion needed

Case G — letters and garbage


Case H — forgetting to convert (the flagship bug)


Case I — the word problem (real-world mix)


Case J — the exam-style twist


Master recall



Connections

  • Parent topic — the golden rule this page stress-tests.
  • Type Conversion (Casting) — the str → float → int two-hop of Case F.
  • String Concatenation vs Arithmetic — why Case H prints 34.
  • Exceptions and try-except — guarding Cases E2 and G.
  • Operators in Python — why Case J's str * int repeats.
  • Variables and Data Types — the str/int/float triad behind every cell.
  • print() Function — the output side of all examples.