Python Basics
Python If...Else
Conditional statements
Python If...Else
Python supports the usual logical conditions from mathematics. These conditions can be used in several ways, most commonly in "if statements" and loops.
If Statement
An "if statement" is written by using the if keyword:
a = 33
b = 200
if b > 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")
Else
The else keyword catches anything which isn't caught by the preceding conditions:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement:
if a > b: print("a is greater than b")
Logical Operators
Python supports logical operators: and, or, not:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")