Operators¶
assignment
math
logic
comparison
identity
membership
Math Operators¶
+
,-
,*
,/
for addition, subtraction, multiplication, & division**
for exponentiation &%
for modulus (remainder)//
for floor division (integer division)
+
, -
, *
, /
for 'sum', 'substract', 'multiply', and 'divide', repsectively.
print(2 + 3)
5
div_result = 4 / 2
print(div_result)
type(div_result)
2.0
float
Order of Operations¶
Mathematical operators follow the rules for order of operations.
follow the rules for order of operations.
parentheses specify which order you want to occur first
order_operations = 3 + 16 / 2
print(order_operations)
11.0
To specify that you want the addition to occur first, you would use parentheses.
specify_operations = (3 + 16) / 2
print(specify_operations)
9.5
Clicker #1¶
What would be the value stored in my_value
?
Note: Best to think about it before running the code to ensure you understand.
my_value = (3 + 2) + 16 / (4 / 2)
my_value
13.0
A) 7.0
B) 10.5
C) 13.0
D) 20.0
E) Produces an error
More Math¶
**
for exponentiation and %
for remainder (called modulus). These also return numbers.
# 2 to the power 3
2 ** 3
8
# remainder of 17 divided by 7
17 % 7
3
Clicker #2¶
What would be the value stored in remainder
?
remainder = 16 % 5
remainder
1
A) 0
B) 1
C) 3
D) 3.2
E) Produces an error
Clicker #3¶
What would be the value stored in modulo_time
?
modulo_time = 4 * 2 % 5
modulo_time
3
A) 0
B) 1
C) 3
D) 3.2
E) Produces an error
Remainder¶
How to get Python to tell you the integer and the remainder when dividing?
The way I first thought of involved a package and we haven’t talked about those yet…
a = 17 // 7
b = 17 % 7
print(a, 'remainder', b)
2 remainder 3
//
is an operator for floor division (integer division)
Clicker #4¶
What value is stored in math_out
from the code below?
math_out = 32 / (1 + 3) ** 2
math_out
2.0
A) 2
B) 16
C) 64
D) This code will fail
Logical (Boolean) operators¶
use Boolean logic
logical operators:
and
,or
, andnot
Booleans are named after the British mathematician - George Boole. He first formulated Boolean algebra, which are a set of rules for how to reason with and combine these values. This is the basis of all modern computer logic.
and
, or
and not
for boolean logic. These operators return booleans.
and
: True if both are trueor
: True if at least one is truenot
: True only if false
True and True
True
True or True
True
True and not False
True
not False
True
# two nots cancel one another out
not (not True)
True
Capitalization matters¶
# this will give you an error
# 'TRUE' is not a boolean
# 'True' is
TRUE and TRUE
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-65-9b3f2ee967bc> in <module>()
2 # 'TRUE' is not a boolean
3 # 'True' is
----> 4 TRUE and TRUE
NameError: name 'TRUE' is not defined
Clicker #5¶
How will the following boolean expression evaluate:
True and False
False
A) True
B) False
C) None
D) This code will fail
Short-circuit evaluation¶
The second argument is evaluated only if the first argument does not definitively determine the value of the expression.
# python stops after False
# no need to check second expression
# since first is False
False and print("Hi")
False
# Continues to evaluate the expression
True and print("Hi")
Hi
# evaluates print statement before and
print("Hi") and False
Hi
Clicker #6¶
How will the following boolean expression evaluate?
True and not True or False
False
A) True
B) False
C) None
D) This code will fail
Clicker #7¶
How will the following boolean expression evaluate:
True and not False
True
A) True
B) False
C) None
D) This code will fail
Comparison Operators¶
==
, !=
, <
, >
, <=
, and >=
for value comparisons. These operators return booleans.
==
: values are equal!=
: values are not equal<
: value on left is less than value or right>
: value on left is greater than value on right<=
: value on left is less than or equal to value on right>=
: value on left is greater than or equal to value on the right
a = 12
b = 13
a > b
False
True == True
True
True != False
True
'aa' == 'aa'
True
12 <= 13
True
Clicker #8¶
Assume you’re writing a videogame that will only slay the dragon only if our magic lightsabre sword is charged to 90 or higher and we have 100 or more energy units in our protective shield.
Start with the code in the following cell. Replace ---
with values that will evaluate to True
when the cell is run (and slay the dragon!).
A) I did it!
B) I tried but am stuck.
C) I’m unsure where to start
## EDIT CODE HERE
sword_charge = 90
shield_energy = 100
alias_a = sword_charge
(sword_charge >= 90) and (shield_energy >= 100)
True
Understanding Boolean logic¶
When first learning booleans, we sometimes think we know what we’re asking the computer to do, but our logic can be flawed.
Let’s look at an example that could trip you up now.
Python considers empty strings as having boolean value of
False
. Non-empty string as having boolean value ofTrue
.
empty_string = ''
bool(empty_string)
False
nonempty_string = 'string has something in it'
bool(nonempty_string)
True
For
and
operator if left value isTrue
, then right value is checked and returned. If left value isFalse
, then that left value is returned.
True and False
False
bool('a')
True
'a' and 'b'
'b'
'b' and 'a'
'a'
Clicker Question #9¶
What would the following code cell return?
'' and 'a'
''
False and 'a'
False
not True and 'a'
False
A) ‘’
B) ‘a’
C)
True
D)
False
# the left value in parentheses is True
'a' == ('b' and 'a')
True
'b' and 'a'
'a'
'a' and 'b'
'b'
# the left value in parentheses is True
'a' == ('a' and 'b')
False
# the left value in parentheses is False
'a' == ('' and 'a')
False
# what we actually wanted python to do
# to look at a in a and b
'a' == 'a' and 'a' == 'b'
False
For
or
operator if left value isTrue
, then it is returned, otherwise if left value isFalse
, then right value is returned.
'a' or 'b'
'a'
# empty string evaluates as False
'' or 'b'
'b'
False or False
False
'' or ''
''
'b' or ''
'b'
'a' == ('a' or 'b')
True
'b' == ('a' or 'b')
False
'b' == 'a' or 'b' == 'b'
True
Clicker Question #10¶
What would the following code cell return?
'a' == ('' or 'a')
True
A) ‘’
B) ‘a’
C)
True
D)
False
Identity Operators¶
Identity operators are used to check if two values (or variables) are located on the same part of the memory.
is
and is not
to compare identity. These operators return booleans.
is
: True if both refer to the same objectis not
: True if they do not refer to the same object
a = 927
b = a
c = 927
print(a is b)
print(c is a)
True
False
Two variables that are equal does not imply that they are identical.
If we wanted that second statement to evaluate as True
we could use is not
…
# make a True statement
print(c is not a)
True
# testing for value equality
a == b == c
True
Clicker #11¶
Using the variables provded below and identity operators replace ---
with code such that true_variable
will return True
and false_variable
will return False
.
A) I did it!
B) I tried but am stuck.
C) I’m unsure where to start
z = 5
x = '5'
c = 'Hello'
d = c
e = [1, 2, 3]
f = [1, 2, 3]
# EDIT CODE HERE
true_variable = c is d
false_variable = z is x
print(true_variable, false_variable)
True False
Delving Deeper: Identity Operators¶
A new object is created each time we have a variable that makes reference to it, but there are few notable exceptions:
some simple strings
Integers between -5 and 256 (inclusive)
empty immutable containers (e.g. tuples) - we’ll get to these later
While these may seem random, they exist for memory optimization in Python implementation.
Shorter and less complex strings are “interned” (share the same space in memory).
The rules behind this are a bit fuzzy, so we’ll just go through a few examples here. But, if you want to read more about string interning and how Python handles this, you can read more here.
simple_string = 'string'
simple_string2 = 'string'
simple_string is simple_string2
True
print(id(simple_string), id(simple_string2))
4429063032 4429063032
longer_string = 'really long string that just keeps going'
longer_string2 = 'really long string that just keeps going'
longer_string is longer_string2
False
print(id(longer_string), id(longer_string2))
4461758576 4461758192
d = 5
e = 5
print(id(d), id(e))
4426314944 4426314944
print(d is e)
True
Python implementation front loads an array of integers between -5 to 256, so these objects already exist.
# Python doesn't create a new object here
j = 5
k = 5
l = 'Hello'
m = 'Hello'
true_variable_integer = j is k
true_variable_string = l is m
print(true_variable_integer, true_variable_string)
True True
# Python DOES create a new object here
n = 975 #greater than 256
o = 975
p = 'Hello!' #that exclamation point makes it more complex
q = 'Hello!'
false_variable_integer = n is o
false_variable_string = p is q
print(false_variable_integer, false_variable_string)
False False
Clicker #12¶
Using the variables provded below and identity operators replace ---
with code such that true_variable
will return True
and false_variable
will return False
.
A) I did it!
B) I tried but am stuck.
C) I’m unsure where to start
a = 5
b = 5
c = b
d = 'Hello!'
e = 'Hello!'
f = 567
g = 567
# EDIT CODE HERE
true_variable = a is b
false_variable = f is g
print(true_variable, false_variable)
True False
Membership Operators¶
in
and not in
to compare membership. These operators return booleans.
Membership operators are used to check whether a value or variable is found in a sequence.
Here, we’ll just be checking for value membership in strings. But, we’ll discuss lists, tuples, sets, and dictionaries soon.
in
: True if value is found in the sequencenot in
: True if value is not found in the sequence
x = 'I love COGS18!'
print('l' in x)
True
print('L' in x)
False
print('COGS' in x)
True
print('CSOG' in x)
False
print(' ' in x)
True
String Concatenation¶
+
on strings does concatenation.
'COGS' + ' 18'
'COGS 18'
'a' + 'b' + 'c'
'abc'
Chaining Operators¶
# Note that you can use parentheses to chunk sections
(13 % 7 >= 7) and ('COGS' + '18' == 'COGS18')
False
(13 % 7 >= 7)
False
('COGS' + '18' == 'COGS18')
True
Clicker #13¶
How will the following expression evaluate:
2**2 >= 4 and 13%3 > 1
a) True
b) False
c) None
d) This code will fail