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.
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.
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.
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).
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.
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 (//).
print(10 // 2)
print(7 // 2)
print(type(7 // 2))Common mistakes
- Mixing up
/and//operators. - Forgetting that division (
/) always results in afloat. - Trying to perform math with text (strings) instead of numbers. Remember to convert if needed!
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.
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.