Arithmetic operators are symbols used to perform mathematical operations on numeric data types such as integers and floats. Python provides the following arithmetic operators:
For example, consider the following Python code
x = 5 y = 2 print(x + y) # Output: 7 print(x - y) # Output: 3 print(x * y) # Output: 10 print(x / y) # Output: 2.5 print(x // y) # Output: 2 (floor division always rounds down) print(x ** y) # Output: 25 (5 squared)
In the above example, the values of x and y are used as operands with the arithmetic operators to perform various mathematical operations. The results of each operation are printed to the console.
The modulus operator (or “mod” for short) is represented by the percent sign (%) and is used to find the remainder after dividing the first operand by the second operand.
For example, if we have two integers a and b, then the mod operator % returns the remainder when a is divided by b. The result of the mod operator will always be less than the second operand b.
Here’s an example:
a = 10 b = 3 remainder = a % b print(remainder) # Output: 1 (10 divided by 3 leaves a remainder of 1)
The mod operator is useful in many scenarios, such as determining if a number is even or odd. For example, if a number is divisible by 2 (i.e., the remainder is 0), then it is even, otherwise, it is odd.
In code, this may look like:
x = 20 if x % 2 == 0: print("The number is even") else: print("The number is odd")
The code above would print out “The number is even” since 20 divided by 2 leaves no remainder. We have not yet looked into if-else statements (conditionals) yet, but this is an example of how we can choose a specific output based on a condition using the mod operator.
Don’t forget PEMDAS! This still applies in Python.