Academic Block

Python Numbers & Math FunctionsGet Certified

What Are Numbers in Python?

Numbers are the values you calculate with: ages, prices, scores, distances, and temperatures. Python has three built-in numeric types. An int is a whole number such as 42 or -7. A float is a number with a decimal point such as 3.14. A complex number has a real and an imaginary part, such as 3 + 4j. The Boolean type bool is a special kind of integer, because True behaves like 1 and False behaves like 0. Python integers have no fixed size limit, so they grow as large as your computer’s memory allows.

  • Numeric types: int, float, and complex, plus bool as a subtype of int.
  • Arithmetic: +, -, *, /, //, %, and **.
  • Float precision: why 0.1 + 0.2 is not exactly 0.3 and how to compare floats safely.
  • Built-in functions: abs(), round(), pow(), min(), max(), sum(), and divmod().
  • The math module: square roots, rounding up and down, logarithms, trigonometry, and constants such as pi.
  • Formatting and statistics: display numbers cleanly and compute averages with the statistics module.

Integers and Floats

You create a number by simply writing it. Python decides the type from how it is written: no decimal point gives an int, and a decimal point or an exponent gives a float. For long numbers you may use underscores as visual separators, as in 1_000_000. Scientific notation uses e, so 2.5e3 means 2.5 times 10 to the power 3, which is 2500.0. The built-in type() function shows the type of a value, and isinstance() tests it.

Try It: Numeric Types

Click Test My Code. Then change big to 1_000.0 and run it again to see how the type changes.

What this code does: It creates an integer, a float, a number with underscore separators, and a number in scientific notation. It prints their types and values, calculates a very large integer, and shows that True behaves like the number 1.
age = 21
price = 19.99
big = 1_000_000
sci = 2.5e3
print(type(age), type(price))
print(big, sci)
print(2 ** 100)
print(isinstance(True, int), True + True)

Arithmetic Operators

Python has seven arithmetic operators. Normal division / always returns a float, even when the numbers divide evenly. Floor division // divides and rounds the result down to the nearest whole number. The modulo operator % returns the remainder, and the two always fit together: a == (a // b) * b + a % b. The ** operator raises a number to a power, and a power of 0.5 is a square root. Operators follow the usual order: parentheses first, then **, then * / // %, and finally + and -.

  • a / b is true division and always gives a float.
  • a // b rounds down toward negative infinity, so -17 // 5 is -4, not -3.
  • a % b takes the sign of b, so -17 % 5 is 3.
  • a ** b is a power. A negative exponent gives a fraction, as in 2 ** -1.
  • divmod(a, b) returns the quotient and the remainder together as a pair.
  • Dividing by zero raises a ZeroDivisionError.

Try It: The Seven Operators

Click Test My Code. Change b to 0 to see a ZeroDivisionError, then change it back.

What this code does: It applies all seven arithmetic operators to two integers. It then shows how floor division and modulo behave with a negative number, calculates powers and a square root, and uses divmod() to get the quotient and remainder in one step.
a = 17
b = 5
print(a + b, a - b, a * b)
print(a / b, a // b, a % b)
print(-17 // 5, -17 % 5)
print(2 ** 10, 2 ** -1, 9 ** 0.5)
print(divmod(a, b))

Floating-Point Precision

Computers store floats in binary, and many decimal fractions such as 0.1 cannot be written exactly in binary. The tiny stored error appears when you print the result of a calculation: 0.1 + 0.2 gives 0.30000000000000004. This is not a Python bug. Every programming language that uses standard floats behaves the same way. There are three safe habits:

  • Never compare floats with ==. Use math.isclose(a, b), which allows for a tiny difference.
  • Round for display. Use round() or an f-string such as {x:.2f} when you show a result.
  • Use Decimal for money. The decimal module stores decimal digits exactly.

Converting a float to an integer with int() does not round. It cuts off the decimal part and moves toward zero, so int(7.9) is 7 and int(-7.9) is -7.

Try It: Why 0.1 + 0.2 Is Not 0.3

Click Test My Code. Notice that three different fixes all lead to the answer you would expect.

What this code does: It shows the small error in 0.1 + 0.2 and that a direct comparison fails. It then fixes the comparison by rounding, by using math.isclose(), and by using exact Decimal values. The last line compares division with int() conversion.
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
import math
print(math.isclose(0.1 + 0.2, 0.3))
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
print(7 / 2, 7 // 2, int(7.9), int(-7.9))

Built-in Math Functions

Python includes several number functions that need no import. abs() returns the absolute value, the distance from zero. round(x, n) rounds to n decimal places, and a negative n rounds to tens, hundreds, and so on. pow(x, y) is the same as x ** y, and pow(x, y, m) returns the remainder after dividing by m. min(), max(), and sum() work on several values or on a whole list.

Note: Python’s round() uses banker’s rounding. A value exactly halfway between two integers goes to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. This reduces bias when many numbers are rounded.

Try It: abs, round, pow, min, max and sum

Click Test My Code. Predict the output of round(4.5) before you try it.

What this code does: It finds absolute values, rounds numbers to different places, calculates powers with and without a modulus, and uses min(), max(), and sum() on a list. It then calculates the average of the list and applies max() and min() to separate values.
print(abs(-7.5), abs(-3))
print(round(3.14159, 2), round(2.5), round(3.5), round(1234, -2))
print(pow(2, 5), pow(2, 5, 7))
nums = [4, 8, 15, 16, 23, 42]
print(min(nums), max(nums), sum(nums))
print(sum(nums) / len(nums))
print(max(3, 9, 5), min("b", "a"))

The math Module

For more advanced calculations, import the math module with import math. It provides the constants math.pi and math.e, and a large set of functions:

  • Roots and powers: sqrt(x) returns a float square root. isqrt(n) returns the whole-number square root of an integer.
  • Rounding: ceil(x) rounds up, floor(x) rounds down, and trunc(x) cuts off the decimal part.
  • Number theory: factorial(n), gcd(a, b) for the greatest common divisor, and lcm(a, b) for the least common multiple.
  • Logarithms: log(x) is the natural logarithm, log10(x) uses base 10, and log2(x) uses base 2.
  • Trigonometry: sin(), cos(), and tan() take angles in radians. Use radians() and degrees() to convert.
  • Geometry: hypot(x, y) returns the length of the hypotenuse of a right triangle.

Try It: Functions from the math Module

Click Test My Code. Try math.sqrt(-1) afterwards and read the error message.

What this code does: It calculates square roots, rounds numbers up, down, and toward zero, prints the constants pi and e, and uses factorial, gcd, and lcm. It also calculates logarithms, the length of a hypotenuse, and the sine of a 30 degree angle.
import math
print(math.sqrt(144), math.isqrt(17))
print(math.ceil(4.2), math.floor(4.8), math.trunc(-4.8))
print(math.pi, math.e)
print(math.factorial(5), math.gcd(12, 18), math.lcm(4, 6))
print(math.log10(1000), math.log2(8), math.log(math.e))
print(math.hypot(3, 4), round(math.sin(math.radians(30)), 2))

Complex Numbers and Number Systems

A complex number is written with a j after the imaginary part, such as 3 + 4j. It has the attributes .real and .imag, and abs(z) returns its magnitude. Python can also write integers in other number systems. Binary literals start with 0b, octal with 0o, and hexadecimal with 0x. The functions bin(), oct(), and hex() convert an integer to text in those systems, and int(text, base) converts back.

Try It: Complex Numbers and Bases

Click Test My Code. Then convert your own number to binary with bin().

What this code does: It creates a complex number, prints its parts and its magnitude, and multiplies it by itself. It then converts integers to binary, octal, and hexadecimal text, converts text back to integers, and writes numbers directly as literals in three number systems.
z = 3 + 4j
print(z.real, z.imag, abs(z))
print(z * z)
print(bin(10), oct(10), hex(255))
print(int("ff", 16), int("1010", 2))
print(0b1010, 0o17, 0xFF)

Formatting Numbers

F-strings allow you to control how numbers are displayed, including their decimal places, width, and alignment. You can do this by adding a format specification after the colon inside the curly braces. The most useful ones are:

  • :, adds thousands separators, as in 1,234,567.
  • :.2f shows a fixed number of decimal places, here two.
  • :.1% multiplies by 100 and adds a percent sign.
  • :05d pads an integer with zeros to a width of 5.
  • :b and :x show an integer in binary and hexadecimal.
  • :e shows scientific notation.
  • :>8, :<8, :^8 right-align, left-align, and center a value in 8 characters.

Try It: Number Format Specifications

Click Test My Code. Change .2f to .0f and see how the result changes.

What this code does: It prints one large number with thousands separators and two decimals, a fraction as a percentage, an integer with zero padding and in two other number systems, the same large number in scientific notation, and an integer aligned three ways inside square brackets.
price = 1234567.891
rate = 0.075
n = 42
print(f"{price:,.2f}")
print(f"{rate:.1%}")
print(f"{n:05d} {n:b} {n:x}")
print(f"{price:e}")
print(f"[{n:>8}] [{n:<8}] [{n:^8}]")

Statistics and Random Numbers

Two more standard modules are often used with numbers. The statistics module calculates mean(), median(), mode(), and the standard deviation with stdev() for a sample or pstdev() for a whole population. The random module produces unpredictable numbers: random.random() returns a float from 0 up to 1, random.randint(a, b) returns an integer from a to b including both ends, and random.choice(list) picks one item. Calling random.seed(n) makes the sequence repeatable, which is useful for testing.

Try It: statistics and random

Click Test My Code. The dice roll changes whenever the seed is changed, so the program checks the range of the result instead of printing the roll.

What this code does: It calculates the mean, median, mode, and population standard deviation of a list of eight numbers. It then rolls a die with random.randint() and picks a random color, and checks that each result is a valid one.
import statistics
import random
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(data), statistics.median(data))
print(statistics.mode(data), statistics.pstdev(data))
random.seed(7)
dice = random.randint(1, 6)
print(1 <= dice <= 6)
print(random.choice(["red", "green", "blue"]) in ["red", "green", "blue"])

Try It: A Circle Calculator

The Program Input box is already filled with the radius 5. Click Run Code straight away, then type another radius, such as 2.5, and run it again.

What this code does: It reads a radius, converts it to a float, and uses math.pi to calculate the area and the circumference. It prints both values with two decimals, and uses math.ceil() to print the diameter rounded up to a whole number.
import math
radius = float(input("Enter the radius: "))
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print(f"Area: {area:.2f}")
print(f"Circumference: {circumference:.2f}")
print(f"Rounded up diameter: {math.ceil(2 * radius)}")

Try It: A Compound Interest Calculator

The Program Input box is filled with three lines: 1000, 5, and 10. Click Run Code, then change the values to see how the rate and the number of years affect the result.

What this code does: It reads a starting amount, a yearly interest rate in percent, and a number of years. It applies the compound interest formula, then prints the final amount and the interest earned with thousands separators and two decimals.
principal = float(input("Principal: "))
rate = float(input("Yearly rate (%): "))
years = int(input("Years: "))
amount = principal * (1 + rate / 100) ** years
interest = amount - principal
print(f"Final amount: {amount:,.2f}")
print(f"Interest earned: {interest:,.2f}")
Tip: Keep the full precision during a calculation and round only when you display the result. Rounding at every step makes small errors add up.

Common Mistakes with Numbers

  • Comparing floats with ==: 0.1 + 0.2 == 0.3 is False. Use math.isclose().
  • Forgetting that input() returns text: input() + 1 raises a TypeError. Convert first with int() or float().
  • Expecting / to give an integer: 10 / 2 is 5.0. Use // when you need a whole number.
  • Surprises with negative floor division: -7 // 2 is -4, because it rounds down, not toward zero.
  • Forgetting import math: calling sqrt(16) or math.sqrt(16) without the import raises a NameError.
  • Using degrees in trigonometry: math.sin() expects radians. Convert with math.radians() first.
  • Math domain errors: math.sqrt(-1) and math.log(0) raise a ValueError, because the result is not a real number.
  • Expecting round() to always round half up: round(2.5) is 2, because ties go to the nearest even number.

Key Takeaways

  • Python has int, float, and complex numbers, and integers can be as large as memory allows.
  • / always returns a float, // rounds down, % gives the remainder, and ** is the power.
  • Floats are stored in binary, so compare them with math.isclose() and use Decimal for exact money calculations.
  • abs(), round(), pow(), min(), max(), sum(), and divmod() need no import.
  • The math module adds sqrt(), ceil(), floor(), logarithms, trigonometry, and constants such as pi.
  • F-strings format numbers with separators, decimals, percentages, padding, and alignment.
  • The statistics and random modules cover averages and random choices.

Frequently Asked Questions

What are the number types in Python?

Python has three built-in numeric types: int for whole numbers, float for numbers with a decimal point, and complex for numbers with a real and an imaginary part. The Boolean type bool is a subtype of int, so True equals 1 and False equals 0.

What is the difference between / and // in Python?

The / operator performs true division and always returns a float, so 7 / 2 is 3.5. The // operator performs floor division and rounds the result down to a whole number, so 7 // 2 is 3 and -7 // 2 is -4.

Why does 0.1 + 0.2 not equal 0.3 in Python?

Floats are stored in binary, and numbers such as 0.1 cannot be represented exactly. The small stored error makes 0.1 + 0.2 equal 0.30000000000000004. To compare floats, use math.isclose(), and for exact decimal arithmetic use the decimal module.

How do I round a number in Python?

Use round(x, n) to round to n decimal places, for example round(3.14159, 2) gives 3.14. Use math.ceil() to always round up and math.floor() to always round down. Note that round() sends exact halves to the nearest even number, so round(2.5) is 2.

How do I calculate a square root in Python?

Use math.sqrt(x) after import math, for example math.sqrt(144) returns 12.0. You can also use the power operator, x ** 0.5. For the whole-number square root of an integer, use math.isqrt(n).

How do I get the remainder of a division in Python?

Use the modulo operator %, for example 17 % 5 is 2. To get the quotient and the remainder at the same time, use divmod(17, 5), which returns the pair (3, 2).

How do I convert between int and float in Python?

Use float(x) to convert to a float and int(x) to convert to an integer. The int() function does not round. It cuts off the decimal part, so int(7.9) is 7 and int(-7.9) is -7. Text from input() must be converted with int() or float() before you calculate with it.

How do I format a number with commas or two decimal places in Python?

Use an f-string with a format specification. The expression f”{x:,.2f}” adds thousands separators and shows two decimal places, so 1234567.891 becomes 1,234,567.89. Use f”{x:.1%}” to show a fraction as a percentage.

Ready for the next step?Learn how to make decisions in your programs with conditions.
Next: if, elif & else →