Python

if - elif - else statements ( conditional statements )

Click for All Topics

if - elif - else statements ( conditional statements ) in Python

The if-elif-else statements in Python are used to make decisions based on conditions. The if statement evaluates a condition and executes the associated block of code if the condition is True. If the condition is False, the program checks the next condition in the elif statement. You can have multiple elif statements to check for different conditions. If none of the if or elif conditions are True, the else block is executed as a fallback. This structure allows you to handle different cases and execute specific code based on the conditions met .

Various conditional statements in python:

  • if statement
  • if-else statement
  •  if-else ladder
  • nested-if statement

if statement

An if statement is a programming conditional statement that, if proved true, performs a task or a set of tasks.

Syntax:

if (condition) 
{
  // do something
}
				
					# Welcome to edSlash learning.
if x > 0: print("x is positive")
				
			

If-else statement:

Theif-else statement helps the programmer make a decision in code when there are two possibilities for a scenario. There are different blocks of code based on whether a certain condition is true or false.

💡Note: Logical and conditional expressions can directly be used with if.

Example –

				
					n = 8
if n < 10:
    print("Number is smaller tha  10")
else:
    print("Number is greater than 10")
    
# Output - 
# Number is smaller than 10
				
			
				
					# Example of an if-else statement
temperature = 18
if temperature <= 15:
	print("It's cold. Wear a jacket.")
else:
	print("It's not cold. No need for a jacket.")

# Output -
# It's not cold. No need for a jacket.
				
			

Explanation:

Think of it like choosing whether to wear a jacket or not based on the weather. If it’s cold, you wear a jacket. If it’s not cold, you don’t wear one. That’s “if-else” in action, helping you decide what to do based on a situation.

If: It checks a condition. If the condition is true, it does something specific. If not, it skips that part.

Else: If the “if” condition is false, “else” comes into play. It does something different when the “if” condition isn’t met.

If-else ladder:

It is a sequence of if and else statements used to make multiple decisions, like a staircase of choices. Each step (condition) is checked one by one until a true condition is found, and the corresponding action is taken.

elif : When you have multiple conditions to check, elif helps you test each one separately after the initial if. If the initial if condition is false, elif conditions are evaluated in order. If any “elif” condition is true, its corresponding action is taken. If none are true, the final “else” action (if present) is executed.

💡Note: It is simply that if the previous conditions were not true, then try this one and if this one is also not true then go to else or another elif.

Imagine deciding what jacket to wear based on the weather. You start by checking if it’s very cold (initial “if”). If it’s not very cold, you move on to consider whether it’s just cold enough to need a jacket (first “elif”) and so on.

Ladder if-else example:

				
					# Example of an if-else ladder for the jacket decision

temperature = 18  # Example temperature in Celsius
if temperature <= 5:
	print("It's very cold. Wear a heavy jacket.")
elif temperature <= 15:
	print("It's cold. Wear a jacket.")
elif temperature <= 25:
	print("It's warm. No need for a jacket.")
else:
	print("It's hot. Stay cool!")
print("Have a great day!")   # This line is not part of if else statements

# Output -
# It's warm. No need for a jacket.
# Have a great day!
				
			

Nested-if statement:

A nested if statement is a programming concept where you have an “if” statement (a condition) inside another “if” statement.

  • It’s like a series of decisions within decisions.
  • First, you pick between “A” and “B”.
  • If you choose “A”, you decide between “X” and “Y” for the color.
  • If you chose “B”, you decide between “Z” and “W” for the color. After deciding on the colour, you pick between the brands “P” and “Q”.

Code:

				
					first_choice = input("Choose between 'A' and 'B': ")

if first_choice == 'A':
    color_choice = input("Choose color for 'A' - 'X' or 'Y': ")
    if color_choice == 'X':
        brand_choice = input("Choose brand for 'A' and color 'X' - 'P' or 'Q': ")
    elif color_choice == 'Y':
        brand_choice = input("Choose brand for 'A' and color 'Y' - 'P' or 'Q': ")
    else:
        print("Invalid color choice for 'A'.")
elif first_choice == 'B':
    color_choice = input("Choose color for 'B' - 'Z' or 'W': ")
    if color_choice == 'Z':
        brand_choice = input("Choose brand for 'B' and color 'Z' - 'P' or 'Q': ")
    elif color_choice == 'W':
        brand_choice = input("Choose brand for 'B' and color 'W' - 'P' or 'Q': ")
    else:
        print("Invalid color choice for 'B'.")
else:
    print("Invalid choice. Please choose between 'A' and 'B'.")


# Output -
# Choose between 'A' and 'B': a A
# Choose color for 'A' - 'X' or 'Y': X
# Choose brand for 'A' and color 'X' - 'P' or 'Q': P
				
			

With conditional and logical expressions:

Code example: 

				
					weather = "sunny"
temperature = 28
if weather == "sunny" and temperature > 25:
	print("It's a great day for outdoor activities!")
else:
	print("Maybe another day.")

# Output -
# It's a great day for outdoor activities!
				
			

Explanation:

In this example,

  1. The if statement evaluates the condition weather == “sunny” and temperature > 25.
  2. The logical operator ‘and’ combines two conditions: one checks if the weather is sunny, and the other checks if the temperature is above 25.
  3. If both conditions are true, the code inside the if block is executed, printing a positive message about going outside.
  4. If any of the conditions are false, the code inside the else block is executed, suggesting another day for outdoor activities.

Similarly, we can use other logical statements.

Another example: 

				
					# Using 'or' with an if statement
age = 17
is_student = False
if age < 18 or is_student:
	print("You get a student discount!")
else:
	print("Regular pricing applies.")

# Output -
# You get a student discount!
				
			

Explanation:

In this example,

  1. The if statement evaluates the condition age < 18 or is_student.
  2. The logical operator “or” combines two conditions: one checks if the age is less than 18, and the other checks if the person is a student
  3. If either of the conditions is true, the code inside the if block is executed, informing the person about a student discount.
  4. If both conditions are false, the code inside the else block is executed, indicating regular pricing.
If with ‘not’ keyword

Code:

				
					# Using 'not' with an if statement
is_raining = True
if not is_raining:
	print("It's a sunny day! Enjoy the outdoors.")
else:
	print("Remember to take an umbrella.")

# Output -
# Remember to take an umbrella.
				
			

Explanation:

In this example,

  1. The if statement evaluates the condition that it is not is_raining.
  2. The not operator negates the value of is_raining, meaning it checks if it’s not true (i.e., if it’s false).
  3. If the condition is true (meaning it’s not raining), the code inside the if block is executed, suggesting enjoying the outdoors.
  4. If the condition is false (meaning it’s raining), the code inside the else block is executed, reminding us to take an umbrella.

 

The advantages of Conditional Statements
  • Allows making decisions based on specific conditions.
  • Controls which code block gets executed.
  • Enables handling different scenarios in code.
  • Provides flexibility in program behaviour.
  • Helps manage user interactions and inputs.
  • Simplifies code by preventing unnecessary actions.