Table of contents
  1. if: elif: else: in Python
    1. Some ifelifelse examples

alt text

if: elif: else: in Python

  • if: Checks a condition. If true, runs the code block.
  • elif: Checks another condition if the previous ones were false. Runs the code block if true.
  • else: Runs the code block if all previous conditions were false.

Some ifelifelse examples

#demo.py
def main():
  print(find_email(sys.argv))

# If demo.py file is run directly (not imported as a module), then run the main() function.
if __name__ == "__main__":
  main()

if user_input.lower() == "yes":
    print("blabla")
stock = "APPL"
NASDAQ  = ["FB", "APPL", "NVDIA"]
if stock in NASDAQ:
    print("..")
Code Examples Code Examples
user_input = "Yes"
if user_input.lower() == "yes":
    print("Yes")
else:
    print("No")
                
fruit = "apple"
fruits = ["apple", "banana", "cherry"]
if fruit in fruits:
    print(f"{fruit} is in the list")
else:
    print(f"{fruit} is not in the list")
                
user_input = "Yes"
if user_input.lower() == "yes":
    print("User said yes")
else:
    print("User did not say yes")
                
fruit = "apple"
fruits = ["apple", "banana", "cherry"]
if fruit in fruits:
    print(f"{fruit} is in the list")
else:
    print(f"{fruit} is not in the list")
                
num = 10
if num % 2 == 0:
    print("Even")
else:
    print("Odd")
                
value = "100"
if isinstance(value, str):
    print("Value is a string")
else:
    print("Value is not a string")
                
n = None
if n is None:
    print("n is None")
else:
    print("n is not None")
                
permissions = ['read', 'write']
if 'admin' in permissions:
    print("Has admin access")
elif 'write' in permissions:
    print("Has write access")
else:
    print("Has read-only access")
                
config = {"debug": True}
if config.get("debug"):
    print("Debugging mode is on")
else:
    print("Debugging mode is off")
                
color = "red"
if color == "blue":
    print("Color is blue")
elif color == "red":
    print("Color is red")
else:
    print("Color is neither blue nor red")
                
x = 3
y = "3"
if x == int(y):
    print("Equal values")
else:
    print("Different values")
                
temperature = 35
if temperature > 30:
    print("It's hot")
elif 20 <= temperature <= 30:
    print("It's warm")
else:
    print("It's cold")