Remainder Operator %
The remainder operator %
divides two numbers and returns the remainder.
For example, 10 % 3
returns 1
, which is the remainder when 10 is divided by 3.
Using the Remainder Operator
remainder = 10 % 3
print(remainder) # 1
Applications of the Remainder Operator
TThe remainder operator is often used to determine whether a number is even or odd by checking the remainder when it is divided by 2.
Determine Even or Odd
# Example of determining even or odd
number = 7
# If number is divisible by 2, it's even; otherwise, it's odd
if number % 2 == 0:
print("It's an even number.")
else:
print("It's an odd number.")
It can also be used to find the unit digit of a number by calculating the remainder when it is divided by 10.
Finding the Units Digit
# Finding the units digit of a number
number = 123
ones_place = number % 10
print(ones_place) # 3
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.