Python Numbers and Casting
Python has three number types, and it is easy to convert values from one type to another.
The Three Number Types
| Type | What it holds | Example |
|---|---|---|
int | Whole numbers, positive or negative, any size | 7, -300, 123456789 |
float | Numbers with a decimal point | 2.5, -0.75, 1e3 |
complex | Numbers with an imaginary part (used in science) | 3 + 2j |
Example
students = 35
temperature = 31.6
z = 2 + 3j
print(type(students))
print(type(temperature))
print(type(z))<class 'int'> <class 'float'> <class 'complex'>
1e3 means 1 times 10 to the power 3, which is 1000.0. This style is called scientific notation.
Basic Maths
Example
a = 17
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** 2)22 12 85 3.4 3 2 289
Notice that / always gives a float, even when the answer is whole. // divides and drops the decimal part. % gives the remainder.
Useful Number Functions
Example
print(round(3.14159, 2))
print(round(7.6))
print(abs(-250))
print(max(12, 45, 8))
print(min(12, 45, 8))
print(pow(2, 5))3.14 8 250 45 8 32
Casting: Changing the Type
Casting means converting a value to another type.
| Function | Result | Example |
|---|---|---|
int() | Whole number (cuts off decimals) | int(9.8) gives 9 |
float() | Decimal number | float(4) gives 4.0 |
str() | Text | str(50) gives "50" |
Example
print(int(9.8))
print(int("120"))
print(float(4))
print(float("2.75"))
print(str(50) + " rupees")9 120 4.0 2.75 50 rupees
int() does not round. It simply removes the part after the decimal point.
Why Casting Matters: input()
The input() function reads what the user types, but it always returns a string. To do maths with it, convert it first:
Example
qty = input("How many kg of apples? ") # user types 3
price_per_kg = 280
total = int(qty) * price_per_kg
print(f"Total: Rs {total}")How many kg of apples? 3 Total: Rs 840
Without int(), Python would raise an error, because you cannot multiply text by a number in this way.
Random Numbers
Python has a built-in module called random:
Example
import random
print(random.randint(1, 6)) # like rolling a diceThe result changes every time you run it, a whole number from 1 to 6.
Exercise
Exercise
What does int(7.9) return?
