Python Operators

Python has a wide range of operators over primitive types. We've already worked with =; let's explore some others.

First, mathematical operators:

a: int = 10
b: int = 5

# math operators
sum: int = a + b
subtract: int = a - b
divide: int = a / b
multiply: int = a * b
exponent: int = a ** b
# this one is important in programming 
modulo: int = a % b

# math and assignment operators
a = 10
a -= 5
a += 7
a *= 2
a /= 3
# what is a?

# parentheses mean the same as they do in math
1 + 1
2 * 5 + 7
2 * (5 + 7)

Next, logical operators:

# are they the same value?
1 == 2
10 == 5 + 5
100 != 10
1000 != 10 * ((5 + 3 + 2) ** 2)

# how do they compare?
10 < 5
10 > 5
10 <= 10
10 >= 11
"b" > "a"

# are both statements true?
True and True
True and False
(10 > 5) and (5 < 7)

# is *at least one* statement true?
True or False
True or True
False or False

# reverse a boolean value
not True
not False
not (True and False)
not (True or False)

# DeMorgan's Law - these are equivalent
not ((not True) and (not False))
True or False

Knowledge Check

What is the final value of each variable here?

a = 1 + 1
b = a / 4.0
c = b * 10
d = c % 5
e = (d - 1) * c
f = True and True
g = True and False
h = False or False
i = False or True
j = a > 0
k = b > a
l = (a + b) * 2 == 3
m = False or (False or True)
n = not (not (False and not(False or True))

Exercise

Write a basic calculator app. The app needs to do 3 things:

  1. Take two numbers, a and b, with input()
  2. Add them together
  3. Output the result