Course contentsShow
← Python
Lesson 31 of 1,0601. Foundations and EnvironmentFree lesson

Performing Arithmetic with Mathematical Operators

Apply standard mathematical operators to perform addition, subtraction, multiplication, and division while understanding the resulting data type changes.

Performing Arithmetic with Mathematical Operators

In this lesson, you will learn how to use Python's built-in mathematical operators to perform calculations and understand how they affect the data types of your results.

The Basic Operators

Python uses standard symbols for arithmetic, which behave just like they do on a calculator:

  • + (Addition): Adds two numbers.
  • - (Subtraction): Subtracts the second number from the first.
  • * (Multiplication): Multiplies two numbers.
  • / (Division): Divides the first number by the second.

Observing Data Type Changes

When performing these operations, it is important to watch how Python handles the data types (integers vs. floats). While adding or multiplying two integers will always result in an integer, division is special.

In Python, the / operator always performs "true division." This means that even if you divide two whole numbers that result in a clean whole number, Python will automatically convert the result into a floating-point number (float).

Consider this example:

# Adding two integers
sum_result = 10 + 5    # Result is 15 (int)

# Multiplying two integers
prod_result = 4 * 3    # Result is 12 (int)

# Dividing two integers
div_result = 10 / 2    # Result is 5.0 (float)

In the last line, even though 10 divided by 2 is exactly 5, Python produces 5.0. This is because the division operator is designed to support results that might include decimals, so it defaults to the float type to ensure accuracy.

When you mix integers and floats in any operation—like 5 + 2.0—Python will automatically "promote" the result to a float to maintain precision. Keeping an eye on whether your variable is an int or a float is a vital habit when writing your scripts, as it dictates how your program will handle subsequent calculations.

Key Takeaway: Python’s arithmetic operators work intuitively, but the division operator / will always return a float, even when the numbers divide evenly.