02-numbers-and-casting.py
python-for-j277 / getting-started  ·  Lesson 02
Lesson 02 — Getting started

Numbers & Casting

Do maths in Python, and change a value from one type to another.

Computers are brilliant at arithmetic. Here you will do calculations, then learn casting — converting a value from one type to another, which you need every time a user types a number.

Doing arithmetic

maths.py
print(7 + 3)
print(7 - 3)
print(7 * 3)
print(7 / 3)
Output
10
4
21
2.3333333333333335
How it works
  • +, - and * are addition, subtraction and multiplication.
  • / is division and always gives a decimal answer, even when it divides evenly.

Whole-number division and remainders

divide.py
print(17 // 5)
print(17 % 5)
print(2 ** 5)
Output
3
2
32
How it works
  • // divides and throws away the remainder: 17 ÷ 5 is 3 remainder 2.
  • % (modulo) gives just the remainder: 2.
  • ** raises to a power: 2 to the power 5 is 32.

Two kinds of number

numbers.py
age = 14
height = 1.62
print(age, height)
Output
14 1.62
How it works
  • age holds 14, a whole number called an integer (int).
  • height holds 1.62, a number with a decimal point called a float.
  • Both are numbers, but Python treats them as different types.

Casting: changing the type

Casting converts a value from one type to another. Because input() returns text, you must cast it before you can do maths with it.

casting.py
years = input("How old are you? ")
years = int(years)
next_year = years + 1
print("Next year you will be", next_year)
Output
How old are you? 14
Next year you will be 15
How it works
  • input() hands back text, so "14" is a string, not a number.
  • int(years) casts that text into an integer so we can add to it.
  • Without the cast, years + 1 would cause an error — you cannot add a number to text.
Awkward inputIf the user types something that is not a whole number, like 'ten', int() will cause an error. You will handle awkward input later using selection and loops.

Casting to float, and to text

convert.py
price = float("2.50")
quantity = int("3")
total = round(price * quantity, 2)
print("Total:", total)
print("As text:", str(total))
Output
Total: 7.5
As text: 7.5
How it works
  • float("2.50") turns text into a decimal number.
  • int("3") turns text into a whole number.
  • round(value, 2) rounds to two decimal places.
  • str(total) casts a number back into text — useful when you want to treat it as a string.
Three casts you will use constantlyint() for whole numbers, float() for decimals, and str() for text.

What you have learned

  • Use + - * / // % ** for arithmetic.
  • / always gives a decimal; // gives the whole-number part; % gives the remainder.
  • Whole numbers are int; numbers with a decimal point are float.
  • Casting changes a value's type: int(), float() and str().
  • Always cast the result of input() before doing maths with it.