Python for AIPython for AI
Data Types

Numbers

Working with integers and decimals

In Python, numbers are fundamental for counting, measuring, and performing calculations. Let's dive into how Python handles them.

Two types of numbers

Python has two main types of numbers we'll use a lot: integers and floats. You can think of them like whole numbers and numbers with decimal points.

  • Integers (or int) are whole numbers, like 1, 100, or -5.
  • Floats (or float) are numbers with a decimal part, like 3.14, 0.5, or -2.7.
python
my_integer = 10
my_float = 10.0

print(type(my_integer))
print(type(my_float))

Why two types?

You might wonder why Python needs two types of numbers. It helps with precision and managing computer memory efficiently. Integers are precise for counting, while floats are good for measurements where fractions are common.

Computers store integers and floats differently. Floats can sometimes have tiny precision errors due to how they're represented internally, but for most everyday tasks, this isn't an issue.

Basic math operations

Python can do all the math you'd expect. We use operators like + for addition, - for subtraction, * for multiplication, and / for division.

python
result_add = 5 + 3
result_subtract = 10 - 4
result_multiply = 6 * 2
result_divide = 15 / 3

print(f"Addition: {result_add}")
print(f"Subtraction: {result_subtract}")
print(f"Multiplication: {result_multiply}")
print(f"Division: {result_divide}")

There are also other useful operators: ** for exponents (power) and % for the modulo (remainder after division).

python
power_result = 2 ** 3  # 2 to the power of 3
modulo_result = 10 % 3 # Remainder of 10 divided by 3

print(f"Power: {power_result}")
print(f"Modulo: {modulo_result}")

Integer vs float division

This is a common point where new programmers can get surprised. Normal division (/) always gives you a float, even if the result is a whole number.

python
print(10 / 2)
print(7 / 2)

If you specifically want integer division (discarding any decimal part) and an integer result, use the double slash operator (//).

python
print(10 // 2)
print(7 // 2)
print(type(7 // 2))

Common mistakes

  • Mixing up / and // operators.
  • Forgetting that division (/) always results in a float.
  • Trying to perform math with text (strings) instead of numbers. Remember to convert if needed!
python
num_str = "5"
num_int = 5

# This will cause an error!
# print(num_str + num_int)

# Correct way:
print(int(num_str) + num_int)

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
What is the result of `10 / 4`?
Code challenge
Not started
A rectangle is 7 wide and 3 tall. Print its area.

What's next?

You've learned the basics of Python numbers! Understanding integers and floats is a great start. Next, you'll see how to store these numbers and other types of information efficiently using variables.