PYT100 M2 1 Slides Operators Comparisons
PYT100 M2 1 Slides Operators Comparisons
1
LEARNING OBJECTIVES
2
CONDITIONS
3
LOGICAL COMPARISON OPERATORS
Assume:
Allows for comparisons
var1 = 5 var2 =20
Returns Boolean userinput = "admin" guess = 1
(true/false) Operator Meaning Example Results
> Greater than var1 > 10 False
Can act unexpectedly if
< Less than var2 < 25 True
the comparisons are of Greater than
two different types >=
or equal to
var1 >= var2 False
Less than or
"2" == 2 is False <=
equal to
var1 <= var2 True
userinput !=
!= Not equal to True
"admin"
== Equal to guess == 3 False
4
COMPARISON COMPLETENESS
When using comparison operators, ensure all options are account for
properly
Consider:
if (value > 10):
print(“Greater than 10”)
else:
print(“Less than 10”) # Is this statement true in all cases?
5
COMPARISON COMPLETENESS
6
COMPARISON COMPLETENESS: ELIF
7
LOGICAL OPERATORS: NOT
8
LOGICAL OPERATORS: AND
Connects two
conditionals
9
LOGICAL OPERATORS: OR
Connects two
conditionals
10
LOGICAL OPERATORS: PARENTHESIS
Open (
Close or closed )
Chain many operators together
Clarity or to remove ambiguity
Order of operations (PEMDAS)
Use parentheses to remove
ambiguity
Example:
(user=='admin' or user=='root' ) and
authenticated == True
Can be nested:
>>> True or ((True or False) and False)
True
>>> False or ((True or False) and False)
False
>>> False and ((True or False) and False)
False
>>> True and ((True or False) and False)
False
11
OR: FIRST TRUE IS TRUE
12
AND: FIRST FALSE IS FALSE
13
ARITHMETIC OPERATORS: COMMON MATH OPERATIONS
Addition, + Examples:
Subtraction, - 6+2=8
15 – 7 = 8
Multiplication, *
25 * 3 = 75
Division, / 55 / 5 = 11.0
14
ARITHMETIC OPERATORS: SPECIAL MATH OPERATIONS
Integer Division, //
Equivalent of int(num1/num2)
55//10 = 5 Note: 55/10 = 5.5, but the // returns only the integer part, 5
9//4 = 2 Note: 9/4 = 2.25, but the // returns only the integer part, 4
15
ARITHMETIC OPERATORS: EXPONENTS
Exponent, **
5**2 = 25 Note: This is the equivalent of 5*5
2**4 = 16 Note: This is the equivalent of 2*2*2*2
16