close menu
In-programming--if--elif--and-else In programming if elif and else

In programming if elif and else

13 February 2025

 In programming  if  elif  and else


In programming, if, elif, and else are conditional statements used to execute specific blocks of code based on whether certain conditions are met. Here's a breakdown of each:

1. if statements: 
This checks if a conditional is true. if the condition evalutes to true, the code inside the if block is executed.
Syntax : 
if condition:
   # code to execute if condition is true

2. elif statement:
This stands for "else if". it's used when you want to check multiple conditions. if the condition in the if statementis false, Python will check the elif condition.
Syntax :
if condition:
   # code to execute if condition is true
elif another_condition:
   # code to execute if another_condition is true
    
3. else statement : This is the default block. if none of the if or elif conditions are true, the code inside the else block will be executed.
Syntax :
if condition:
   # code to execute if condition is true
elif another_condition:
   # code to execute if another_condition is true
else:
   # code to execute if no previous conditions were true

Example:
age = 20

if age < 18:
   print("You are a minor.")
elif age >= 18 and age < 60:
   print("You are an adult.")
else:
   print("You are a senior citizen.")

In this example:
- If age is less than 18, it prints "You are a minor."
- If age is between 18 and 59, it prints "You are an adult."
- If none of the above conditions are true (i.e.,age is 60 or more), it prints "You are a senior citizen."

Whatsapp logo