Numbers in Python

Python supports several types of numbers, including integers, floats, and complex numbers. These types allow you to perform various mathematical operations and are essential in both basic and advanced computations.

Integers:

Integers are whole numbers without a decimal point. You can perform arithmetic operations such as addition, subtraction, multiplication, and division with integers. Python's integers are of arbitrary precision, meaning they can handle very large numbers.

Python
a = 10
b = 5

print(a + b)  # Output: 15
print(a - b)  # Output: 5
print(a * b)  # Output: 50
print(a / b)  # Output: 2.0

Floats:

Floats are numbers with a decimal point. They are used when precision is required, such as in calculations involving currency, measurements, or scientific computations.

Python
x = 3.14
y = 1.5

print(x * y)  # Output: 4.71
print(x / y)  # Output: 2.0933333333333333

Complex Numbers:

Python also supports complex numbers, which have a real part and an imaginary part. They are particularly useful in advanced mathematical computations, such as in engineering and physics.

Python
z = 2 + 3j
print(z.real)  # Output: 2.0
print(z.imag)  # Output: 3.0

Type Conversion:

You can convert between different numeric types using Python's built-in functions. For example, you can convert an integer to a float or vice versa:

Python
a = 5  # Integer
b = float(a)  # Convert to float
c = int(b)  # Convert back to integer

print(b)  # Output: 5.0
print(c)  # Output: 5

Checking the Type:

Use the type() function to check the type of a number:

Python
print(type(a))  # Output: 
print(type(b))  # Output: 
print(type(z))  # Output: 

Mathematical Functions:

Python provides several built-in mathematical functions that work with numbers, such as:

Python
print(abs(-7))  # Output: 7
print(round(3.14159, 2))  # Output: 3.14
print(pow(2, 3))  # Output: 8

Real-World Applications:

Each type of number in Python serves different purposes:

Python's ability to handle different types of numbers makes it versatile for a wide range of applications, from basic arithmetic to complex mathematical modeling.