Introduction:
Welcome to your next Python adventure! Today, we’re going to explore how to use arithmetic operators in Python to perform basic calculations. Arithmetic operators allow us to add, subtract, multiply, divide, and even raise numbers to a power, just like you would in mathematics.
Real-World Application Example:
Arithmetic operators are used everywhere! Whether you’re calculating the total cost of shopping items, working out a budget, or figuring out how much interest you’ll earn on a savings account, these operators are essential.
Here’s a quick example of arithmetic operators in action:
print(5 + 3) # Addition: prints 8 print(10 - 2) # Subtraction: prints 8 print(4 * 7) # Multiplication: prints 28 print(16 / 4) # Division: prints 4.0 print(2 ** 3) # Exponentiation: prints 8 (2 to the power of 3)
Why Casting is Important:
In Python, when you input numbers from a user, they are always treated as strings. But when you need to perform calculations on these inputs (such as addition or multiplication), they must be converted into the right type—either integers (int) or floats.
For example:
num1 = input("Enter a number: ") # Input is stored as a string print(num1 + num1) # This will just repeat the string, not add the numbers!
If you try to add num1
to itself without converting it, the output will be the string repeated, rather than the correct sum.
Here’s how you would fix it:
num1 = int(input("Enter a number: ")) # Now it's an integer print(num1 + num1) # This will add the numbers correctly
Tip: You can use int()
to convert to integers, or float()
to work with decimal numbers.
Predict:
What do you think the following code will output? Think carefully about how each arithmetic operator works:
print(6 + 4) print(12 - 8) print(5 * 3) print(16 / 2) print(3 ** 2)
Take a moment to predict the output before moving on. Hint: These operations should feel familiar—they work just like maths you do every day!
Run:
Now it's time to test some arithmetic operations! Run the following code to see how Python handles addition, subtraction, multiplication, division, and exponentiation:
Notice how Python performs these operations and displays the results. Addition and subtraction are straightforward, but did you see how division always returns a decimal (a float)?
Investigate:
Let’s investigate how Python handles division in more detail. Run the code below and observe the difference between normal division and integer division.
Normal division (/) will give you the exact result, including decimals. But integer division (//) will round the result down to the nearest whole number. Try changing the numbers and running the code again.
What do you notice?
The output from the Integer Division is...an Integer!
Modify:
Here’s a piece of code that has a small mistake. Can you fix it so that it works correctly?
Hint: Replace the subtraction operator (-) with the correct arithmetic operator to make it an addition.