Python by example

Operators in Python

Basic operations can be performed on variables of the same type using operators.

sum = 5 + 3
difference = 5 - 3
product = 5 * 3
division = 5 / 3

Simple operations can be performed on the change of variables, by using the following shorthand operators:

x = 5
x += 3 # x = x + 3
x -= 3 # x = x - 3
x *= 3 # x = x * 3
x /= 3 # x = x / 3

Additional operators can be used to perform more complex operations:

# Exponentiation
exponentiation = 5 ** 3 # 5^3=125
# Floor division
floor_division = 5 // 3 # 5 divided by 3, rounded down to the nearest integer = 1
# Modulus
modulus = 5 % 3 # 5 divided by 3, remainder = 2

Python also provides comparison operators to compare two values:

# Equal
is_equal = 5 == 3
# Not equal
is_not_equal = 5 != 3
# Greater than
is_greater_than = 5 > 3
# Less than
is_less_than = 5 < 3
# Greater than or equal to
is_greater_than_or_equal_to = 5 >= 3
# Less than or equal to
is_less_than_or_equal_to = 5 <= 3
Next example: Loop