Chapter 5: Numbers and Math

Numbers are fundamental to programming. They let you model real‑world quantities like money, scores, measurements, and more. Python handles numerical data with ease and provides powerful tools for mathematical operations. In this chapter, you’ll learn about Python’s numeric types and how to perform calculations with them.

In this chapter you will learn:

5.1 Numbers in Python

Python supports three main numeric types: integers, floating‑point numbers, and complex numbers. For most programming tasks, you’ll work primarily with integers and floats.

Integers (int)

Integers are whole numbers without decimal points. They can be positive, negative, or zero:

>>> 42
42
>>> -17
-17
>>> 0
0

There’s no limit to how large an integer can be in modern Python — you can store enormous values without worrying about overflow:

>>> 2 ** 100
1267650600228229401496703205376

Floating‑Point Numbers (float)

Floating‑point numbers (also called floats) represent decimal values. They are used for measurements, currency, and other values that need precision beyond whole numbers:

>>> 3.14159
3.14159
>>> -2.5
-2.5
>>> 0.0
0.0

You can also use scientific notation for very large or very small numbers:

>>> 1.23e4
12300.0
>>> 5.67e-3
0.00567

Float arithmetic can sometimes produce small rounding errors due to how computers represent decimal numbers in binary. For financial applications requiring perfect precision, use the decimal module.

Complex Numbers (complex)

Python also supports complex numbers for mathematical and scientific computing. Complex numbers have a real part and an imaginary part:

>>> 3 + 4j
(3+4j)
>>> (2 + 3j) * (1 - 2j)
(8-1j)

Determining Number Types

Use the type() function to check what kind of number you’re working with:

>>> type(42)

>>> type(3.14)

>>> type(2 + 3j)

5.2 Arithmetic Operations

Python supports all basic arithmetic operations you’d expect from a calculator plus some additional ones that prove useful in programming.

Basic Operators

Here are Python’s arithmetic operators:

Operator Description Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3.333...
// Floor division 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 3 8

Mixed‑Type Operations

When you mix integers and floats in an expression, Python automatically converts the integers to floats before performing the operation:

>>> 10 + 3.14
13.14
>>> type(10 + 3.14)

Working with the Math Module

Python’s built‑in math module provides many advanced mathematical functions and constants. To use it, you need to import it first:

import math

print(math.pi)      # 3.141592653589793
print(math.e)       # 2.718281828459045
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2))  # 4
print(math.floor(3.8)) # 3

Common Math Functions

Here are some of the most useful functions in the math module:

Angles are expressed in radians in the math module, not degrees. Use math.radians() to convert degrees to radians before using trig functions.

Mathematical Constants

5.3 Type Conversion with Numbers

Sometimes you need to convert between different numeric types. Python provides built‑in functions for this purpose.

Converting to Integers

Use int() to convert floats or strings representing whole numbers to integers. The fractional part is truncated (not rounded):

>>> int(3.14)
3
>>> int(3.9)
3
>>> int("42")
42

Converting to Floats

Use float() to convert integers or numeric strings to floating‑point numbers:

>>> float(42)
42.0
>>> float("3.14")
3.14

Precision in Escaping Types

When converting from float to int, you lose decimal precision. You can round first if you want to preserve the nearest whole number:

price = 29.99
dollars = int(price)                             # 29
dollars = round(price)                           # 30

5.4 Challenge: Multiply Calculator

Write a program called multiply.py that asks the user for two numbers and then displays the product of those two numbers.

The program should:

  1. Prompt the user for the first number with "Enter first number: "
  2. Prompt the user for the second number with "Enter second number: "
  3. Convert the input strings to floats using float()
  4. Multiply the two numbers and display the result with two decimal places
Enter first number: 3.5
Enter second number: 4
The product is: 14.00

Complete Program

first = float(input("Enter first number: "))
second = float(input("Enter second number: "))
product = first * second
print(f"The product is: {product:.2f}")

Review Exercises

  1. Write a program that calculates and displays the area of a circle given the radius entered by the user. Use math.pi.
  2. Create a program that converts temperature from Celsius to Fahrenheit using the formula F = C × (9/5) + 32.
  3. Write a script that calculates compound interest using the formula A = P(1 + r/n)^(nt) where P is principal, r is annual rate, n is compounding frequency, and t is time in years.
  4. Use the math module to calculate the hypotenuse of a right triangle given the two legs as input (a² + b² = c²).

5.5 Understanding Floating-Point Precision

When working with floating-point numbers, you may encounter some unexpected behavior due to how computers represent decimal numbers in binary.

It is well known that some decimal numbers cannot be represented exactly in binary. For example, dividing 1 by 3 gives a repeating decimal in decimal (0.333...), but in binary, dividing 1 by 10 gives a repeating binary fraction.

This can lead to what appears to be incorrect calculations:

>>> 0.1 + 0.2 0.30000000000000004 >>> 0.1 + 0.2 == 0.3 False

Python, like most programming languages, uses IEEE 754 floating-point arithmetic, which can introduce small rounding errors in calculations.

Rounding to Fix Precision Issues

When precision matters, you can use the round() function to round to a specific number of decimal places:

>>> round(0.1 + 0.2, 1) 0.3 >>> total = 0.1 + 0.2 >>> round(total, 2) 0.3

For applications requiring exact decimal representation, such as financial calculations, use the decimal module:

from decimal import Decimal >>> Decimal('0.1') + Decimal('0.2') Decimal('0.3') >>> Decimal('0.10') + Decimal('0.20') Decimal('0.30')

5.6 Summary and Additional Resources

100%