BYU logo Computer Science

Operators

We previously covered types and operators to demonstrate how different types support different operations. We now want to show you a more complete list of operators.

Arithmetic Operators

Arithmetic operators take two numbers and produce a result.

OperatorExampleResult
+7 + 29
-7 - 25
*7 * 214
/7 / 23.5
**7 ** 249
//7 // 23
%7 % 21

Addition, subtraction, multiplication, and division are straightforward.

Exponentation ** raises the first number to the power of the second. So 7 to the power of 2 is 49.

Integer division //, also called floor division, gives the integer portion of a division operation.

Modulation % gives the remainder of a division operation.

All of these operations can be used in the following ways. First, directly using numbers:

if __name__ == '__main__':
    print(5 + 7)

Second, within a function:

# within a function
if __name__ == '__main__':
    number = 5
    print(number + 7)

Third, using variables:

# using variables
if __name__ == '__main__':
    number = 5
    number = number + 7
    print(number)

Comparison operators

OperatorExampleResult
>2 > 1True
<2 < 1False
>=2 >=2True
<=2 <= 2True
==4 == 4True
!=4 != 6True

We use == to check for equal to and != to check for not equal to.