Python if elif else


if, elif, and else Statements in Python

The if, elif, and else statements in Python are used to implement conditional logic in your programs. They allow you to execute different blocks of code based on the evaluation of boolean expressions (conditions).

Syntax

if condition1: # Execute this block if condition1 is True elif condition2: # Execute this block if condition1 is False and condition2 is True else: # Execute this block if both condition1 and condition2 are False

Explanation of Components

  1. if statement: This checks the first condition. If the condition evaluates to True, the block of code following it is executed.

  2. elif statement: This stands for "else if." It checks another condition if the previous if condition was False. You can have multiple elif statements to check for various conditions.

  3. else statement: This block is executed if all preceding conditions (if and elif) evaluate to False. The else block is optional.

Example of if, elif, and else

Here’s a simple example to illustrate how these statements work:

# Input: a score from a student score = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F")

Explanation of the Example

  • The program checks the value of score.
  • If score is greater than or equal to 90, it prints "Grade: A".
  • If the first condition is False, it checks the second condition (elif score >= 80). If this is True, it prints "Grade: B".
  • This process continues until it finds a True condition or reaches the else block.
  • If none of the conditions are met, it defaults to printing "Grade: F".

More Complex Example

You can also use logical operators (like and and or) to combine multiple conditions. Here’s a more complex example:

age = 20 has_ticket = True if age >= 18 and has_ticket: print("You can enter the concert.") elif age >= 18 and not has_ticket: print("You need a ticket to enter.") elif age < 18 and has_ticket: print("You can enter the concert, but you need a guardian.") else: print("You cannot enter the concert.")

Explanation of the Complex Example

  • The program checks if the person is at least 18 years old and has a ticket.
  • If both conditions are met, it prints "You can enter the concert."
  • If the age condition is met but the ticket condition is not, it prints "You need a ticket to enter."
  • If the person is under 18 but has a ticket, it prints "You can enter the concert, but you need a guardian."
  • If none of these conditions are met, it defaults to printing "You cannot enter the concert."

Summary

  • The if, elif, and else statements allow you to control the flow of your program based on conditions.
  • You can have multiple elif statements and only one else statement.
  • These statements help in creating decision-making capabilities in your Python programs, making them more interactive and dynamic.