Conditional Logic with If Statements
- February 26, 2018
- Key Terms: math
Boolean Expressions¶
A boolean expression always evaluates to be True
or False
.
You can evaluate a boolean expression with a ==
operator.
"dan" == "dan"
3 == 3
3 == 7
True
and False
are of type bool
.
type(True)
Relational operators¶
Relational operators evaluate expressions to be True
or False
.
All examples below evaluate to True
operator | code example | code description |
---|---|---|
== | 8 == 8 | 8 is equal to 8 |
!= | 7 != 8 | 7 is not equal to 8 |
> | 4 > 2 | 4 is greater than 2 |
< | 3 < 5 | 3 is less than 5 |
>= | 10 >= 9 | 10 is greater than or equal to 9 |
<= | 6 <= 6 | 6 is less less than or equal to 6 |
Remember =
is an assignment operator in Python while a ==
is a relational operator.
Logical Operators¶
All examples below evaluate to true.
operator | code example | code description |
---|---|---|
and | 3 > 2 and 5 > 4 | 3 is greater than 2 and 5 is greater than 4 |
or | 5 > 4 or 3 > 4 | 5 is greater than 4 or 3 is greater than 4 |
not | not 4 > 6 | not 4 is greater than 6 - two negatives make a positive |
Conditional Execution¶
In programming, it's helpful to check conditions to change the behavior of programs and output relevant results. Conditional statements give us this ability.
if 8 > 5:
print("8 is greater than 5")
The boolean of 8 > 5
after the if
is called the condition.
Chained conditionals¶
Sometimes, there are two or more conditionals to be evaluated.
Let's say I ask you to guess a number between 0 and 10 and your goal is to guess correctly. You guess 6 first and the correct number is 9.
guess = 6
if guess < 9:
print("you guessed too low")
elif guess > 9:
print("you guessed too high")
else:
("you're correct!")
elif
is an abbreviation for else if. We could have additional elif
statements if needed.
Our program will evaluate in this order:
1) Variable guess
is assigned to the value of 6
2) The if
statement is evaluated to True and we print the statement in its body.
However, let's say your next guess is 9.
guess = 9
if guess < 9:
print("you guessed too low")
elif guess > 9:
print("you guessed too high")
else:
print("you're correct!")
Our program will evaluate in this order:
1) Variable guess
is assigned to the value of 10
2) The if
statement is evaluated to False
so we don't proceed to its indented body
3) The elif
statement is evaluated to False
so we don't proceed to its indented body
4) Once reached, the else
statement always evaluates to True
so we proceed to its indented body and print that string.