Understanding how to work with numbers and perform arithmetic operations is fundamental to programming. Python provides a variety of numeric types and a rich set of operators for working with them.
Python supports both integers (whole numbers) and floating point numbers (decimals). You can perform basic arithmetic operations such as addition, subtraction, multiplication, and division with these numbers.
# Integer arithmetic
result = 5 + 7
print(result)
# Float arithmetic
result = 10.5 - 3.2
print(result)
Division in Python can be done with the /
operator. If you want to perform a floor division,
which rounds
the result down to the nearest integer (or the largest integer less than or equal to the result), you can
use the //
operator.
# Regular division
result = 8 / 3
print(result)
# Floor division
result = 8 // 3
print(result)
The modulus operator %
returns the remainder of a division, while the exponent operator **
raises a number to the power of another number.
# Modulus
remainder = 8 % 3
print(remainder)
# Exponent
result = 2 ** 3
print(result)
Python also supports complex numbers with real and imaginary parts. For instance, if we have a complex
number z
defined as z = 1 + 2j
, we can access the real part 1
by printing z.real
.
# Working with complex numbers
z = 1 + 2j
print(z.real)
print(z.imag)