If Statements
If Statement videos
Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements
if/elif/else
and
,or
,not
is
andid()
“Truthy” and “Falsey” Values
Comparison operators
> # greater than
< # less than
>= # greater than or equal to
<= # less than or equal to
== # equal to
!= # not equal to
is # used to check equality for True, False, and None
in # determines if something is in a collection
if, else
age = int(input("Please enter your age: "))
if age >= 18:
print("You can vote")
else:
print("You can not vote.")
if, elif, else
mark = int(input("Please enter your mark: "))
if mark >= 80:
print("You have an A")
elif mark >= 70:
print("You have a B")
else:
print("You have a C or lower.")
Multiple elif
mark = int(input("Please enter your mark: "))
if mark >= 80:
print("You have an A")
elif mark >= 70:
print("You have a B")
elif mark >= 60:
print("You have a C")
elif mark >= 50:
print("You have a D")
else:
print("You FAIL!!!!")
Boolean values in variables
age = 10
old_enough = age > 5
if old_enough is True:
print("You can ride on the rollercoaster!")
Boolean operators
We need to be able to reproduce these truth tables.
AND
Both inputs need to be True
. Think: “Both And”.
A |
B |
A and B |
---|---|---|
True |
True |
True |
True |
False |
False |
False |
True |
False |
False |
False |
False |
OR
Either can be True
. Think: “Either Or””.
A |
B |
A or B |
---|---|---|
True |
True |
True |
True |
False |
True |
False |
True |
True |
False |
False |
False |
NOT
Inverts the Boolean value.
A |
not A |
---|---|
True |
False |
False |
True |
Boolean operators in if statements
a = 5
b = 7
if a >= 5 and b > 10: # False
print("hello")
if a == 5 or b > 100: # True
print("goodbye")
if not (a >= 5 and b > 10): # True
print("hello")