Number Types in Python

This notebook introduces Python’s built-in number-related types: integers, floats, and complex numbers, along with type conversion, type checking, and small exercises.

Integers (int)

Integers are whole numbers (positive, negative, or zero) without decimal points.

Examples:

a = 10
b = -5
c = 0
print(a, b, c)
10 -5 0

Exercise: Create two integer variables and print their sum.

x = 7
y = 12
print("Sum:", x + y)
Sum: 19

Floating Point Numbers (float)

Floats are numbers with decimal points or in scientific notation.

Examples:

pi = 3.14159
tax_rate = 0.07
distance = -2.5
avogadro = 6.022e23
print(pi, tax_rate, distance, avogadro)
3.14159 0.07 -2.5 6.022e+23

Exercise: Create a float variable for temperature and print it in a sentence using an f-string.

temperature = 23.5
print(f"The current temperature is {temperature}°C.")
The current temperature is 23.5°C.

Complex Numbers (complex)

Complex numbers have a real and imaginary part, written as a + bj.

Examples:

z1 = 2 + 3j
z2 = 1 - 4j
print("z1:", z1)
print("z2:", z2)
print("Sum:", z1 + z2)
z1: (2+3j)
z2: (1-4j)
Sum: (3-1j)

Why Use j for Complex Numbers in Python?

In mathematics, the imaginary unit is often written as i. However, in engineering, i is commonly used to represent electric current. To avoid confusion, Python uses j to represent the imaginary unit (√-1).

Example: - 1j means the imaginary number 0 + 1×j. - 2 + 3j means a complex number with real part 2 and imaginary part 3.

# Complex number example with j
z = 2 + 3j
print(z)        # prints 2 + 3j

# Accessing real and imaginary parts
print("Real part:", z.real)
print("Imaginary part:", z.imag)
(2+3j)
Real part: 2.0
Imaginary part: 3.0

Exercise: Create two complex numbers and multiply them.

z1 = 2 + 3j
z2 = 1 - 4j
result = z1 * z2
print("Multiplication result:", result)
Multiplication result: (14-5j)

Type Conversions

Convert between number types using int(), float(), and complex().

print(int(3.7))
print(float(5))
print(complex(2, 3))
3
5.0
(2+3j)

Exercise: Convert an integer to a float and a float to an integer, then print the results.

my_int = 10
my_float = 5.99

converted_to_float = float(my_int)
converted_to_int = int(my_float)

print("Integer to float:", converted_to_float)
print("Float to integer:", converted_to_int)
Integer to float: 10.0
Float to integer: 5

Checking Types

print(type(10))
print(type(3.14))
print(type(2+3j))
<class 'int'>
<class 'float'>
<class 'complex'>

Exercise: Use type() to check the type of a number you define.

value = 42.0
print(type(value))
<class 'float'>

Common Pitfalls

print(0.1 + 0.2 == 0.3)  # Floating-point precision issue
print(5 / 2)             # Division returns float
print(5 // 2)            # Floor division returns int
False
2.5
2