Chapter 07

Taking input from the person using your program

Reading what someone types with input(), why it is always a str, and which errors show up when you convert it with int() and float().

30 minPython 3.12
  1. 1Encounter
  2. 2Understand
  3. 3Worked
  4. 4Predict
  5. 5Apply
  6. 6Stretch

The problem we are solving

Every program so far had its numbers written inside the file. To run it with different numbers you had to open the file and edit it.

Real programs do not work that way. A program asks, and the person using it answers.

In Python, asking is the job of input(). It takes a minute to learn. But it comes with one rule that traps every new programmer at least once: whatever input() returns is always text — even when the person typed a perfectly good number. Not knowing that one rule is enough to break your first calculating program.

By the end of this mission you can

  • Read what someone types with input(), showing a clear question
  • Explain why input is always a str
  • Convert it to a number with int() and float()
  • Tell TypeError and ValueError apart
  • Clean input so a stray space does not break your program

Prerequisites: Working with text — indexing, slicing, and f-strings.


How input() works

python
name = input("What is your name? ")
print(f"Hello, {name}!")

Run it:

text
What is your name? Rafi
Hello, Rafi!

Three things happened. input() showed the question in the parentheses; then it stopped and waited until the person typed something and pressed Enter; then it handed back what was typed, and we stored that in name.

Note the space at the end of the question — "What is your name? ". Without it, what the person types is jammed up against the question mark and looks wrong.

These programs have to be run in the terminal. input() waits for someone to type, so it does not work on a website or in an editor preview pane. Run python ask.py in your own terminal — which is how this whole course works anyway.

The rule that traps everyone once

python
age = input("Your age: ")
print(type(age))
print("Next year:", age + 1)
text
Your age: 22
<class 'str'>
Traceback (most recent call last):
  File "D:\python-lab\lesson-07\ask.py", line 3, in <module>
    print("Next year:", age + 1)
                        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

The person typed 22. The screen shows a number. And type(age) says str.

The reason makes sense once you think about it: a keyboard produces characters, not numbers. Someone might type 22, or abc, or 12.5. input() could have guessed — "that looks numeric, I will convert it" — but then the same line of code would return a str sometimes and an int other times, and you could never know which in advance. So Python keeps one rule: always text. Converting is your job.

int() and float()

python
age = input("Your age: ")
age = int(age)

print(type(age))
print("Next year:", age + 1)
text
Your age: 22
<class 'int'>
Next year: 23

The two steps fit on one line, and that is how it is usually written:

python
age = int(input("Your age: "))
print("Next year:", age + 1)

Read it inside out: input() produced text, int() turned it into a whole number, and the result went into age.

For decimals, float():

python
price = float(input("Price: "))
print("With tax:", round(price * 1.15, 2))
text
Price: 249.50
With tax: 286.92

Which to use: int for things you count (ages, counts, quantities), float for things you measure (prices, weights, averages).

Two errors, two different causes

These two names are easy to confuse, so look at them side by side.

TypeError — the kind of thing is wrong. You tried to add a number to text, having forgotten the conversion entirely:

python
qty = input("Quantity: ")
print(qty * 2)
text
Quantity: 3
33

Notice there was no error this time. "3" * 2 means the text twice — "33". The program ran and the answer is wrong. A silent wrong answer is worse than an error.

ValueError — the kind is right, but the text is not a number:

python
age = int(input("Your age: "))
text
Your age: twenty
Traceback (most recent call last):
  File "D:\python-lab\lesson-07\ask.py", line 1, in <module>
    age = int(input("Your age: "))
          ^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'twenty'

int() is willing to do the job, just not with 'twenty'. The message even names the offending value, in quotes at the end.

A subtle but very real trap:

python
count = int(input("Count: "))

Type 12.5 and this raises ValueError too — because int() does not accept text with a decimal point in it. If decimals are possible, take it with float() and convert to int() afterwards if you need to.

We do not yet have everything needed to prevent these errors — that takes both conditions and loops, and both are in missions ahead. For now, recognise the error and learn to read the message.

Clean the input

People type extra spaces and mix capitals. The tools from the last mission are exactly what is needed:

python
full_name = input("Name: ").strip().title()
answer = input("Continue? (yes/no) ").strip().lower()

print(f"Name is {full_name}")
print(f"Answer is {answer}")
text
Name:    rafi ahmed
Continue? (yes/no)   YES
Name is Rafi Ahmed
Answer is yes

Make .strip() on anything from input() a habit. There is no reason for a program to break over one extra space.


A complete example

bill.py:

python
# Ask for one order and print a small bill
print("--- Order entry ---")

customer = input("Customer name : ").strip().title()
item = input("Item          : ").strip()
quantity = int(input("Quantity      : "))
unit_price = float(input("Unit price    : "))

subtotal = quantity * unit_price
tax = subtotal * 0.05
total = subtotal + tax

print()
print("--- Bill ---")
print(f"Customer : {customer}")
print(f"Item     : {item} x {quantity}")
print(f"Subtotal : {subtotal:.2f}")
print(f"Tax (5%) : {tax:.2f}")
print(f"Total    : {total:.2f}")
text
--- Order entry ---
Customer name :   rafi ahmed
Item          : notebook
Quantity      : 4
Unit price    : 85.50

--- Bill ---
Customer : Rafi Ahmed
Item     : notebook x 4
Subtotal : 342.00
Tax (5%) : 17.10
Total    : 359.10

Four inputs, four different treatments: the name is cleaned and capitalised, the item only cleaned, the quantity converted to a whole number, the price to a decimal. For every input you have to decide two things — which type you need, and how to clean it.


When it breaks

TypeError: can only concatenate str (not "int") to str The conversion is missing. Write int(input(...)) or float(input(...)).

I meant to multiply, but the text is repeating "3" * 2 gives "33". The value was never converted to int. This bug is dangerous precisely because no error appears — when in doubt, print type().

ValueError: invalid literal for int() with base 10 What the person typed is not a whole number — a word, a decimal, or nothing at all (just Enter). If decimals are possible, use float().

The program is just sitting there showing nothing It is waiting for your input. With no question given to input(), nothing appears on screen and it looks stuck. Always pass a question.

input() does not work inside my editor Some editors and online blocks cannot take input. Open a terminal and run python bill.py.

There is an extra blank line after I press Enter input() takes your text and does not keep the trailing newline. An extra blank line is almost certainly from a print() of your own.