Lesson 3: Operators

In this lesson, we wil learn about...

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Membership operators

Arithmetic Operators

These are used with numbers to perform mathematical operations.

In [1]:
x = 5
y = 3

print( x + y )
print( x - y )
print( x * y )
print( x / y )
print( x % y )
print( x ** y )
print( x // y )
8
2
15
1.6666666666666667
2
125
1

Assignment Operators

These work like the arithmetic operators, but variable being assigned is part of the equation.

In [2]:
x = 5
x += 3
print(x)

x = 5
x -= 3
print(x)

x = 5
x *= 3
print(x)
8
2
15
In [3]:
x = 5
x /= 3
print(x)

x = 5
x %= 3
print(x)

x = 5
x **= 3
print(x)

x = 5
x //= 3
print(x)
1.6666666666666667
2
125
1

Comparison Operators

These are used to compare two values, and always return a bool. They become more useful when we talk about if...else and loops later on.

In [4]:
print( 3 == 5 )
print( 3 != 5 )
print( 3 > 5 )
print( 3 < 5 )
print( 3 >= 5 )
print( 3 <= 5 )
False
True
False
True
False
True

Logical Operators

These are primarily used in if...else and loops to combine multiple expressions.

In [5]:
print( True and False )
print( True or False )
print( not True )
False
True
False

and Truth Table

x y x and y
True True True
True False False
False True False
False False False

or Truth Table

x y x or y
True True True
True False True
False True True
False False False

Membership Operators

These are used to test if a sequence is present in an object. Recall that we saw this with strings, and will again with more complex data structures.

In [6]:
print( "e" in "Hello" )
print( "e" not in "Hello" )
True
False

Order of Operations

  1. Parenthesis
  2. Exponents
  3. Multiplication, Division, Modulus
  4. Addition, Subtraction
  5. Comparisons, Membership, Identity
  6. not
  7. and
  8. or