Find a course

Module 2: Working With Numbers and TextLesson 5 of 1211 min

User Input and Type Conversion

Read input from users, convert text to int and float safely, understand ValueError, and combine everything into a small working calculator program.

Step 1 of 13Learn

input() always gives you text

Programs get far more interesting when they respond to the person using them. The built-in input() function shows a prompt, waits for the user to type something and press Enter, and returns what they typed:

name = input("What's your name? ")
print(f"Nice to meet you, {name}!")

So far, so good. Now try a calculation:

age = input("How old are you? ")    # user types 30
print(age + 1)

This crashes with TypeError: can only concatenate str (not "int") to str. The reason is the most important fact about input(): it always returns a string. The user typed the characters "3" and "0", so age is "30", text, and Python won't add a number to text.

Even more confusing, some code with this bug doesn't crash. If you write age * 2, Python repeats the string and gives "3030". And age + age gives "3030" too. No error, just wrong answers.

The fix is to convert the string to a number before doing math. That's the subject of this lesson, and forgetting it is the single most common beginner bug in programs that read input.

Step 2 of 13Learn

Converting between types

Python's type names double as conversion functions:

CallResultNotes
int("42")42text to whole number
float("3.75")3.75text to decimal number
int(3.99)3float to int drops the decimals
str(42)"42"number to text
float(5)5.0int to float
int(" 42 ")42surrounding spaces are fine
int("4.5")ValueErrorint() won't parse a decimal string
int("forty")ValueErrornot a number at all

The usual pattern wraps input() directly:

age = int(input("How old are you? "))
print(f"Next year you'll be {age + 1}.")

Choose the conversion that matches the data. Counts and ages: int. Prices, weights and measurements: float, because users will type decimals. Passing "4.5" to int() raises a ValueError; if you really want an int from it, convert in two steps, int(float("4.5")), which gives 4.

bool() converts too, but with a twist: it doesn't read the words. Any non-empty string is True, including "False" and "0"; only the empty string "" is False. For numbers, 0 and 0.0 are False and everything else is True. To interpret a typed yes or no, compare the text instead: answer.strip().lower() == "yes".

Step 3 of 13Practice · Diagram

From keyboard to calculation

A user types “ten”. At which step does the program crash?

Tap the shape that answers the question, then press Check.

From keyboard to calculationProcess diagram: input() returns text → int() or float() converts → Do the math → f-string shows the result.input()returns textint() orfloat()convertsDo the mathf-string showsthe result
input() returns text

Even if the user types 5, you get the string "5".

int() or float() converts

Raises ValueError if the text is not a valid number.

Do the math
f-string shows the result

Step 4 of 13Practice · What would you do?

What would you do?

A user runs this program and types 5 at the prompt.

qty = input("How many tickets? ")
total = qty * 12
print(total)

What happens?

Step 5 of 13Learn

A complete program: splitting a bill

Here is a small but complete program that combines everything so far: input, conversion, arithmetic and formatted output.

# Split a restaurant bill
bill = float(input("Bill amount: "))
tip_percent = float(input("Tip percent (e.g. 18): "))
people = int(input("Number of people: "))

tip = bill * tip_percent / 100
total = bill + tip
per_person = total / people

print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Each person pays: {per_person:.2f}")

Walk through it as the interpreter would. Each input() returns text, which is converted immediately: float for money and percentages, int for the number of people. The tip percentage is divided by 100, because a user types 18, not 0.18. Then the totals are calculated, and f-strings with :.2f display money with exactly two decimals.

Notice the structure, which almost every small program shares: input, then processing, then output. Keeping these three parts separate makes programs easier to read and to change. Suppose you later want to round each share up to the next whole dollar so nobody underpays. You'd change one line in the processing part, using math.ceil from the math module (Module 5), without touching input or output.

Try running it with a bill of 84.50, an 18% tip and 3 people.

Step 6 of 13Try the calculator

Bill splitter (the same math as the program)

These inputs mirror the three input() calls. The outputs match what the program prints.

Tip: bill * tip_percent / 100
15.21 $
Total: bill + tip
99.71 $
Each person pays: total / people
33.24 $

Step 7 of 13Practice · Work it out

What is the value of float("2.5") * 4?

Step 8 of 13Learn

When conversion fails: ValueError

What if the user types "ten" or "12 dollars" when your program expects a number? int("ten") raises:

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

A ValueError means the type is right (it's a string) but the content can't be converted. Programs that read input must expect this, because users mistype, paste extra text or press Enter without typing anything (which gives the empty string "", also a ValueError for int()).

There are two broad strategies:

  1. Check first. For whole numbers, text.isdigit() returns True only if every character is a digit. It's simple but limited: it rejects "-5" and "3.5".
  2. Try it and handle the failure. Attempt the conversion and catch the ValueError if it happens. This is the Python style, written with try and except, and you'll learn it properly in Module 5. Combined with a loop (Module 3), it lets a program keep asking until it gets valid input.

Also clean input before converting or comparing: input().strip() removes accidental spaces. int() and float() already ignore surrounding spaces, but string comparisons such as checking for "yes" do not, so stripping is a good habit everywhere.

Step 9 of 13Flashcards

Conversion results

Tap a card to flip it.

Step 10 of 13Note

Step 11 of 13Practice · Put in order

Put these lines in order to make a program that asks for two whole numbers and prints their sum.

Drag the items, or use the arrow buttons, to put them in order.

  1. b = int(input("Second number: "))
  2. total = a + b
  3. a = int(input("First number: "))
  4. print(f"The sum is {total}")

Step 12 of 13Practice · True or false

bool("False") evaluates to False.

Step 13 of 13Practice · Choose one

A program asks for the price of an item, and users may type values like 19.99. Which line reads the price correctly as a number?