2a: Comparisons and conditionals
Table of Contents
🎉Table of contents with working links🎉
1. Homework check?
2. Bit more about booleans
2.1. Boolean value
check = True print(type(check))
(N.B.: not how we can check the data type of the variable!)
2.2. Boolean expressions:
An expression is a combination of variables, operators, and values that lead to a single result.
A boolean expression is an expression that is either true or false: it leads to a boolean value.
Last Friday: boolean expressions with relational operators:
print(5 >= 3)
Today we add: boolean expressions with logical operators that allow us to combine boolean values and/or expressions:
- and
- or
- not
#print(not False or False) print(3 > 2 and 4 > 5)
Note that logical operators are meant to work with boolean values or expressions.
- But Python is tolerant and will also treat …
- … the integer 0
- … the float 0.0
- … the string ""
- … as False.
- The rest of the integers, floats and strings are treated as True
if "hi all": print("this is true")
3. Conditionals
3.1. Conditional execution
Simplest form of an if-statement:
if 0: print("this is considered as True")
Tip for assignment:
x = 1 if isinstance(x, str): print("it's a string") elif isinstance(x, float): print("it's a float") elif isinstance(x, bool): print("it's a boolean") elif isinstance(x, int): print("it's an integer") else: print("it's not one of the fourt primive data types")
3.2. Alternative execution
num1 = 5 num2 = 3 if num1 > num2: print("num1 is bigger than num2") else: print("num2 is bigger than num1")
3.3. Chained conditions
When there are more than two possibilities, we can use a chained conditional:
num1 = 3 num2 = 3 if num1 > num2: print("num1 is bigger than num2") elif num2 > num1: print("num2 is bigger than num1") elif num1 == num2: print("num1 is the same as num2")
3.4. Nested conditional
cond1 = 1 > 0 cond2 = 3 < 4 if cond1: print("😖") if cond2: print("it's break time!!")
When possible, it's better to avoid nested conditionals.
This …
x = 5 if 3 < x < 10: print("x is between 3 and 10")
… is better than this:
x = 5 if x > 3: if x < 10: print("x is between 3 and 10")
You could now already design a simple game!
4. The "in" operator
The "in" operator tests if the value to the left side of the operator is found in a "collection" to the right side of the operator.
var1 = [1,2,"hi",True] if "hi" in var1: print("var1 contains hi") else: print("var1 does not contain hi")