Examples of if... else in Python programming

0

The if…elif…else statement is used in Python for decision making.

Example :

if test expression:
    statement(s)

All Contributions

Program to tell the user wich letter he choose :

letter = "A"
if letter == "B":
  print("letter is B")  
else :     
  if letter == "C":
    print("letter is C")    
  else:      
    if letter == "A":
      print("letter is A")      
    else:
      print("letter isn't A, B and C")

Program to check if x = 4 and prints a message to tell the user that if it's or is not :

x = 3
if x == 4:
   print("Yes")
else:
   print("No")

Program to input a number and check if the number is positive or negative or zero and display an appropriate message :

This time we use nested if statement''

num = float(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

program to check if the number is positive or negative or zero and display an appropriate message :

num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

Program checks if the number is positive or negative And displays an appropriate message :

num = 3
# Try these two variations as well. 
# num = -5
# num = 0
if num >= 0:
    print("Positive or Zero")
else:
    print("Negative number")

total contributions (6)

New to examplegeek.com?

Join us