livepython.net
CHAPTER 07Getting Input from the User
7.2  CONVERT INPUT

Convert Input to Numbers with int() and float()

Whole Numbers: int(input())

To get a whole number from the user, wrap input() in int():

PYTHONedit me
age = int(input())
print("Next year you will be", age + 1)
OUTPUT
Next year you will be 26

This works in two steps, from the inside out:

  1. input() reads the text "25".
  2. int() turns it into the number 25.

Now age + 1 is real maths: 26.

Think of it as an assembly line: the user's text goes into input(), comes out as a string, goes straight into int(), and comes out as a number.

Adding two numbers, properly this time

PYTHONedit me
a = int(input())
b = int(input())
print(a + b)
OUTPUT
5

Compare this with the last topic, where the same numbers gave 23. The only difference is int().

Two lines or one?

You can also convert in a separate step. Both versions do the same thing:

One lineTwo lines
age = int(input())text = input() then age = int(text)

The one-line version is shorter, and it's what most Python programmers write.

Common beginner doubt: "Do spaces around the number matter?" No: int() ignores spaces at the start and end, so " 25 " still becomes 25.

int(input()) reads what the user types and turns it into a whole number.

your turnPredict the output

What will this print?

n = int(input()) print(n * 2)

The user types: 7

Your turn! What will this code show on the screen?
your turnFix the code

Make it print the sum: 15

It should print: 15

The user types: 105

a = input()
b = input()
print(a + b)
This code does not work yet. Fix it, then press Run.

Decimal Numbers: float(input())

For numbers that can have a decimal point, like prices, heights or temperatures, use float() instead:

PYTHONedit me
price = float(input())
print("With tax:", price * 1.1)
OUTPUT
With tax: 22.0

float() accepts whole numbers too: the text "20" becomes 20.0.

int or float?

The user typesUseWhy
an age, a count, a number of itemsint(input())whole numbers only
a price, a weight, a temperaturefloat(input())may have a decimal point

If you're not sure, ask: "Could someone type a decimal here?" If yes, use float().

Show neat results

Calculations with floats can give long decimals. Use :.2f from chapter 5 to show two decimal places:

PYTHONedit me
price = float(input())
qty = int(input())
print(f"Total: {price * qty:.2f}")
OUTPUT
Total: 59.97

Notice that one program can mix int() and float(): the price can have decimals, the quantity can't.

Think of a shop's scale and a shop's counter: the scale shows grams with decimals (float), the counter shows whole items (int).

Use float(input()) when the user might type a decimal number.

your turnType the output

Type what this prints

h = float(input()) print(h * 2)

The user types: 1.5

Read the code line by line, then type the output exactly.
your turnPick the right idea

Which conversion fits a weight in kilograms, like 62.5?

Think about it, then pick one.

When Conversion Fails

What if the user types something that isn't a number? The conversion fails, and Python stops with a ValueError:

PYTHONedit me
age = int(input())
print(age)
OUTPUT
ValueError: invalid literal for int() with base 10: 'twenty'

You met this message in chapter 5: "invalid literal for int()" means "this text isn't a whole number".

The common surprises

The user typesint()float()
252525.0
2.5ValueError2.5
25 (spaces)2525.0
twentyValueErrorValueError
nothing (empty line)ValueErrorValueError

The one that catches people most: int() can't read "2.5". If decimals are possible, use float().

Think of a ticket machine that only takes coins: hand it a note, and it beeps and stops.

What can you do about it?

For now, two things:

  • Use clear prompts that say what to type: "Age (a whole number): ".
  • Pick the right conversion: float() when decimals are possible.

In the Exceptions chapter, you'll learn to catch a ValueError and ask the user again, instead of letting the program stop.

If the text isn't a number, int() and float() stop with a ValueError.

your turnPredict the output

What will this print?

x = int(input()) print(x)

The user types: 2.5

Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

The user types: Sunnyten

One line stops this program. Tap it.

Calculating with Input

Now you can build programs that do real calculations with the user's numbers. The pattern is always the same:

  1. Read the values with int(input()) or float(input()).
  2. Calculate with them.
  3. Show the result, neatly.
PYTHONedit me
length = float(input())
width = float(input())
area = length * width
print(f"Area: {area:.1f} square metres")
OUTPUT
Area: 10.0 square metres

Change the numbers in the Input box: the same program works for every room.

Another example: average of three marks

PYTHONedit me
a = int(input())
b = int(input())
c = int(input())
average = (a + b + c) / 3
print(f"Average: {average:.2f}")
OUTPUT
Average: 84.33

Remember the brackets from chapter 5: without them, only c would be divided by 3.

Think of a calculator with labelled buttons: the user only presses the numbers; your program knows what to do with them.

Check with easy numbers first

Before trying "real" numbers, test with numbers you can check in your head, like 2 and 3. If the program says the area of 2 by 3 is 6, you can trust it with 4.25 by 3.75.

Read, calculate, show: the shape of almost every input program.

your turnOrder the lines

Put the lines in order to double a number

  1. print("Double:", double)
  2. n = int(input())
  3. double = n * 2

The user types: 7

These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

print(f"{7 / 2:.1f}")
Your turn! What will this code show on the screen?

Practice: Convert input

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 53.Python Program to Add Two Numbers from InputEasySolve
  2. 54.Python Program to Find a Rectangle's Area from InputEasySolve
  3. 55.Python Program to Convert Celsius to Fahrenheit from InputMediumSolve