Python Tutorial menu

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

TypeWhat it holdsExample
intWhole numbers, positive or negative, any size7, -300, 123456789
floatNumbers with a decimal point2.5, -0.75, 1e3
complexNumbers with an imaginary part (used in science)3 + 2j

Example

python
students = 35
temperature = 31.6
z = 2 + 3j
print(type(students))
print(type(temperature))
print(type(z))
Output
<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

python
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)
Output
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

python
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))
Output
3.14
8
250
45
8
32

Casting: Changing the Type

Casting means converting a value to another type.

FunctionResultExample
int()Whole number (cuts off decimals)int(9.8) gives 9
float()Decimal numberfloat(4) gives 4.0
str()Textstr(50) gives "50"

Example

python
print(int(9.8))
print(int("120"))
print(float(4))
print(float("2.75"))
print(str(50) + " rupees")
Output
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

python
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}")
Output
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

python
import random
print(random.randint(1, 6))   # like rolling a dice

The result changes every time you run it, a whole number from 1 to 6.

Exercise

Exercise

What does int(7.9) return?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp