Python if Else
Python if Else
If statements
An "if statement" is written by using the if keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
a = 33 a = 33
b = 200 b = 200
if b > a: if b > a:
print("b is greater than a") print("b is greater than a")
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
The else keyword catches anything which is not caught by the preceding
conditions.
a = 200 a = 200
b = 33 b = 33
if b > a: if b > a:
print("b is greater than a") print("b is greater than a")
elif a == b: else:
else:
print("a is greater than b")
The and keyword is a logical operator, and is used to combine conditional
statements:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
The or keyword is a logical operator, and is used to combine conditional
statements:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
The not keyword is a logical operator, and is used to reverse the result of the
conditional statement:
x = True
print(not x)
You can have if statements inside if statements, this is called nested if statements
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass