Python Beginner Tutorial # 3: if, Else, Elif Statements

If Statement

if statements are typically used with logical operators

x = 10
y = 15
if y > x:
  print("y is greater than x")

a = 50
b = 25
if b < a:
  print("a is greater than b")
  if a !=b:
       print("Not Equal")

Output :
y is greater than x
a is greater than b
Not Equal

Elif

Elif statements tell Python what to do when condition is False

a = 50
b = 25
if b == a:
  print("Equal")
elif a != b :
      print("Not Equal")
Output :
Not Equal

Else

can be added after Elif statement or can be use with an if statement by itself

a = 50
b = 25
if b == a:
    print("Equal")
elif a <= b :
    print("Equal")
else :
    print("Not Equal")

x = 50
y = 45
if y > x:
    print("y Greater than")
else :
    print("x Greater than")
Output :
Not Equal
x Greater than

Multiple if Statements

x = 20
y = 75
if x > y: 
 print("X Greater")
if y > x:  
     print("y Greater")
Output :
y Greater

Nested If

Is an if statement with in another if statement.

Revenue = 500

if Revenue > 100:
  print("Fair")
  if Revenue > 200:
    print("Good")
  else:
    print("$$$")
Output :
Fair
Good
Click here for Part Five : List