Conditional Logic
Conditional Logic
if, elif, else
ifexecutes code if the condition is True.- If
ifis False,elifchecks condition(s) in order (there can be multipleelifstatements). elseruns only if all previous conditions are False.
Combine checks
- Use
and,or,notto combine conditions.
Truthy & Falsy
- In Python, most values are considered truthy.
- Exceptions (considered falsy):
None,False, numbers equal to zero, and empty data types ([],{},'', etc.).
is_old = 'hello' # truthy
is_licensed = 0 # falsy
print(bool(is_old)) # True
print(bool(is_licensed)) # False
if is_old and is_licensed: #if true and true print code
print('you can drive now')
elif is_licensed: #elif print this
print('you can\'t')
else: #else print this
print('you can\'t')
Ternary Operator (Conditional Expression)
A shorthand way to write conditional logic. Syntax: value_if_true if condition else value_if_false Does not support elif.
is_friend = False
can_message = 'message allowed' if is_friend else "not allowed to message"
print(can_message)
Short Circuiting
Python stops evaluating logical expressions once the result is determined.
- With or: stops at the first True.
- With and: stops at the first False
— it doesn’t evaluate the rest of the expression unnecessarily.
Using 'or' → stops when it finds the first True
x = True or print("This won't run") #(nothing printed, because True is enough to decide result)
Using 'and' → stops when it finds the first False
y = False and print("This won't run") #(nothing printed, because False is enough to decide result)
not Operators
- Returns the opposite Boolean value.
print(not False)
print(not True)
== vs is
- == checks Value equality
- is checks Object identity (same memory reference)
(is) checks, whether this is in the same memory space, same bookshelf as that one
print(True is 1) #checks for exact same thing, located in different memory space
print(True == 1) #checks for the values
Logical Operator
- <, >, ==, >=, <=, !=
- and, or, not, is
- Used in conditional logic to control program flow.
In Python, they let the program skip or execute lines depending on whether conditions are True or False.
Walrus Operator(:=)
- Assigns values within expressions.
- to do something based on a condition and then calculate that value again.
a = 'hellooooooo'
if (n := len(a)) > 10:
print(f'the elements {n} are too long')
while ((n:= len (a)) > 1):
print(n)
a = a[:-1]
print(a)