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().
- 1Encounter
- 2Understand
- 3Worked
- 4Predict
- 5Apply
- 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()andfloat() - Tell
TypeErrorandValueErrorapart - Clean input so a stray space does not break your program
Prerequisites: Working with text — indexing, slicing, and f-strings.
How input() works
name = input("What is your name? ")
print(f"Hello, {name}!")Run it:
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. Runpython ask.pyin your own terminal — which is how this whole course works anyway.
The rule that traps everyone once
age = input("Your age: ")
print(type(age))
print("Next year:", age + 1)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 strThe 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()
age = input("Your age: ")
age = int(age)
print(type(age))
print("Next year:", age + 1)Your age: 22
<class 'int'>
Next year: 23The two steps fit on one line, and that is how it is usually written:
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():
price = float(input("Price: "))
print("With tax:", round(price * 1.15, 2))Price: 249.50
With tax: 286.92Which 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:
qty = input("Quantity: ")
print(qty * 2)Quantity: 3
33Notice 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:
age = int(input("Your age: "))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:
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:
full_name = input("Name: ").strip().title()
answer = input("Continue? (yes/no) ").strip().lower()
print(f"Name is {full_name}")
print(f"Answer is {answer}")Name: rafi ahmed
Continue? (yes/no) YES
Name is Rafi Ahmed
Answer is yesMake .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:
# 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}")--- 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.10Four 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.
Step 4 of 6 — Predict
Check your understanding
The person types 42 and presses Enter. What does the second line print?
value = input("Number: ")
print(type(value))- A<class 'str'>
- B<class 'int'>
- C<class 'float'>
- D<class 'input'>
The person typed 3 and the program printed Doubled: 33, with no error at all. Why, and what fixes it?
qty = input("Quantity: ")
print("Doubled:", qty * 2)- A`qty` is a `str`, and multiplying text by a number repeats it — it needs `int(qty) * 2`
- BThe `print` needs a `+` instead of a comma
- CWriting `qty + qty` instead of `qty * 2` would fix it
- D`input()` cannot read numbers, so a different function is needed
What happens if the person types 12.5?
count = int(input("Count: "))
print(count + 1)- AA `ValueError` — `int()` does not accept text with a decimal point; take it with `float()` if decimals are possible
- B`count` becomes `12`, because `int()` cuts off everything after the point
- C`count` becomes `13`, because `int()` rounds to the nearest whole number
- DA `TypeError`, because the input and the variable types do not match
Answering needs an account
Sign in to check your answers
The questions are above, and working them out in your head is the part that matters. Sign in to see the answers, the explanations and the three-level hints.
Your turn
Write a file called travel.py that asks four questions and shows a small calculation:
- The passenger's name (cleaned, capitalised)
- How many passengers (a whole number)
- The fare per passenger (a decimal)
- The discount rate as a percentage (a decimal)
Then print the total fare, the discount amount, and the final amount due — all three to two decimal places.
When it works, try to break it three times on purpose:
- Type
twofor the number of passengers — which error appears, and what does the message say? - Type
2.5for the number of passengers — what happens, and why? - Put a few spaces before and after the name — does the output survive?
If the answer to the last one is yes, you are already writing better code than the average beginner. The fixes for the other two arrive once you have conditions and loops.
There is more in this mission
What you read above is the complete mission — nothing was cut out of it. Pro adds:
- What actually happens underneath — how Python runs this
- The full solution to the exercise, worked step by step
- Harder extra exercises
- The interview question on this topic, with a model answer
Step 6 of 6
Stretch — the chapter quiz
Ten questions from easy to hard. The last ones are difficult on purpose.
Sign in to take the quiz