Conditional Logic with If Statements¶
Date published: 2018-02-26
Category: Python
Subcategory: Beginner Concepts
Tags: math
Boolean Expressions¶
A boolean expression always evaluates to be True
or False
.
You can evaluate a boolean expression with a ==
operator.
"dan" == "dan"
True
3 == 3
True
3 == 7
False
True
and False
are of type bool
.
type(True)
bool
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")
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!")
you guessed too low
elif
is an abbreviation for else if. We could have additional elif
statements if needed.
Our program will evaluate in this order:
Variable
guess
is assigned to the value of 6The
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!")
you're correct!
Our program will evaluate in this order:
Variable
guess
is assigned to the value of 10The
if
statement is evaluated toFalse
so we don't proceed to its indented bodyThe
elif
statement is evaluated toFalse
so we don't proceed to its indented bodyOnce reached, the
else
statement always evaluates toTrue
so we proceed to its indented body and print that string.