= 5 # Assign the integer 5 to the variable a
a == 6 # Then check its value compared to 6 a
False
Comparison operations compare some value or operand and based on a condition, produce a Boolean.
Most of us have been seeing these operators for decades. Nothing new in Python, (just note the use of = as it is not a comparison operator, but an assignment), when comparing two values you can use these operators:
==
!=
>
<
>=
<=
assignment: =
I will not go into much detail here, just one quick example
Note: operators can be applied to strings just as well as they are applied to numbers
Here we see the corresponding ASCII values of letters
Char. | ASCII | Char. | ASCII | Char. | ASCII | Char. | ASCII |
---|---|---|---|---|---|---|---|
A | 65 | N | 78 | a | 97 | n | 110 |
B | 66 | O | 79 | b | 98 | o | 111 |
C | 67 | P | 80 | c | 99 | p | 112 |
D | 68 | Q | 81 | d | 100 | q | 113 |
E | 69 | R | 82 | e | 101 | r | 114 |
F | 70 | S | 83 | f | 102 | s | 115 |
G | 71 | T | 84 | g | 103 | t | 116 |
H | 72 | U | 85 | h | 104 | u | 117 |
I | 73 | V | 86 | i | 105 | v | 118 |
J | 74 | W | 87 | j | 106 | w | 119 |
K | 75 | X | 88 | k | 107 | x | 120 |
L | 76 | Y | 89 | l | 108 | y | 121 |
M | 77 | Z | 90 | m | 109 | z | 122 |
Allows us to run different statements for different inputs. This is your typical if statement, if you’re familiar with other programming languages. Usually conditional comparisons and operators are used to test a condition prior to executing a command (or several commands)
Note: Indentation is extremely important in Python, in R the command(s) to be executed are enclosed in {} so there is no mistake what is done if the condition is met. In Python, the indentation tells Python what needs to be executed if the condition is met. So all commands need to be indented if they are conditional commands
if condition statement:
Note: if is lower case
age = 19
if age > 18:
print("Yeehaw, I can drink. Oh wait that was 30 years ago!")
print("This will print regardless of condition because it is NOT indented")
Yeehaw, I can drink. Oh wait that was 30 years ago!
This will print regardless of condition because it is NOT indented
else
runs a block of code if none of the conditions are True before this else
statement\:
in the else:
elif
is short for else if, gives us another way to string along additional branches/conditional statements before exiting out to the else:
elif
is True then that block of code is executedSometimes you want to check more than one condition at once. For example, you might want to check if one condition and another condition are both True. Logical operators allow you to combine or modify conditions. I’m not going to spend much time on this, as it’s logic 101 learned before you were allowed to drink.
and
or
not
Note: use lower case (unlike R)