An Introduction to the Art of Computer Programming Using Python in the Age of Generative AI

II. Numbers and Arithmetic

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.

Integers and Floats

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 and Floor Division

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)
        

Modulus and Exponents

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)
        

Complex Numbers

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)
        
Back to Home