Learn Python 3 - Control Flow Cheatsheet - Codecademy
Learn Python 3 - Control Flow Cheatsheet - Codecademy
Control Flow
SyntaxError
elif Statement
or Operator
The Python or operator combines two Boolean True or True # Evaluates to True
expressions and evaluates to True if at least one of
True or False # Evaluates to True
the expressions returns True . Otherwise, if both
expressions are False , then the entire expression
False or False # Evaluates to False
evaluates to False . 1 < 2 or 3 < 1 # Evaluates to True
3 < 1 or 1 > 6 # Evaluates to False
1 == 1 or 1 < 2 # Evaluates to True
Equal Operator ==
c = '2'
d = 2
if c == d:
print('They are equal')
else:
print('They are not equal')
if val1 != val2:
print("They are NOT equal")
if Statement
test_string = "VALID"
if test_string == "NOT_VALID":
print("String equals NOT_VALID")
else:
print("String equals something else!")
and Operator
The Python and operator performs a Boolean True and True # Evaluates to True
comparison between two Boolean values, variables, or
True and False # Evaluates to False
expressions. If both sides of the operator evaluate to
True then the and operator returns True . If either False and False # Evaluates to False
side (or both sides) evaluates to False , then the and 1 == 1 and 1 < 2 # Evaluates to True
operator returns False . A non-Boolean value (or 1 < 2 and 3 < 1 # Evaluates to False
variable that stores a value) will always evaluate to
True when used with the and operator. "Yes" and 100 # Evaluates to True
Boolean Values
Booleans are a data type in Python, much like integers, is_true = True
floats, and strings. However, booleans only have two
is_false = False
values:
True
False print(type(is_true))
Specifically, these two values are of the bool type.
# will output: <class 'bool'>
Since booleans are a data type, creating a variable that
holds a boolean value is the same as with other data
types.
not Operator
The Python Boolean not operator is used in a Boolean not True # Evaluates to False
expression in order to evaluate the expression to its
not False # Evaluates to True
inverse value. If the original expression was True ,
including the not operator would make the expression 1 > 2 # Evaluates to False
False , and vice versa. not 1 > 2 # Evaluates to True
1 == 1 # Evaluates to True
not 1 == 1 # Evaluates to False
Print Share