Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python if else statement

The if and else statements in Python are used to control the flow of your program based on specific conditions. They allow you to execute different blocks of code depending on whether a given condition is True or False.

Here's a tutorial on how to use the if, elif, and else statements in Python:

  • Basic Syntax

The basic syntax for the if statement is as follows:

if condition:
    # code to execute if condition is True

The condition is any Python expression that evaluates to a boolean value (True or False). If the condition is True, the indented block of code underneath it will be executed.

  • Using the if statement

Here's an example of using the if statement:

age = 18

if age >= 18:
    print("You are an adult.")

In this example, the if statement checks whether the age is greater than or equal to 18. If the condition is True, the print() statement is executed.

  • Using the else statement

The else statement is used to specify a block of code to be executed if the condition in the if statement is False.

if condition:
    # code to execute if condition is True
else:
    # code to execute if condition is False

Here's an example of using the if and else statements together:

age = 15

if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

In this example, the if statement checks whether the age is greater than or equal to 18. If the condition is True, the first print() statement is executed; otherwise, the second print() statement is executed.

  • Using the elif statement

The elif (short for "else if") statement is used to specify multiple conditions. It allows you to check for several conditions in a single if statement.

if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition2 is True
else:
    # code to execute if none of the conditions are True

Here's an example of using the if, elif, and else statements together:

grade = 75

if grade >= 90:
    print("You got an A.")
elif grade >= 80:
    print("You got a B.")
elif grade >= 70:
    print("You got a C.")
elif grade >= 60:
    print("You got a D.")
else:
    print("You got an F.")

In this example, the if and elif statements check the value of the grade variable and execute the corresponding print() statement based on the grade range.

In summary, the if, elif, and else statements in Python allow you to control the flow of your program based on specific conditions. These statements are fundamental to programming in Python and are essential for writing clean and efficient code.

  1. How to use if-else in Python:

    • Description: Use if-else to conditionally execute different blocks of code based on a specified condition.
    • Code:
      x = 10
      if x > 5:
          print("Greater than 5")
      else:
          print("5 or less")
      
  2. Conditional branching with if-else in Python:

    • Description: Branch code execution based on a specified condition using if-else.
    • Code:
      age = 25
      if age >= 18:
          print("Adult")
      else:
          print("Minor")
      
  3. Using logical operators in if-else statements:

    • Description: Combine conditions using logical operators (and, or, not) in if-else statements.
    • Code:
      x = 10
      if x > 5 and x % 2 == 0:
          print("Greater than 5 and even")
      else:
          print("Not greater than 5 or not even")
      
  4. Nested if-else statements in Python:

    • Description: Nest if-else statements to handle multiple conditions.
    • Code:
      x = 10
      if x > 5:
          if x % 2 == 0:
              print("Greater than 5 and even")
          else:
              print("Greater than 5 but not even")
      else:
          print("5 or less")
      
  5. Chaining multiple conditions with if-else in Python:

    • Description: Chain multiple if-else statements to handle a series of conditions.
    • Code:
      x = 10
      if x > 10:
          print("Greater than 10")
      elif x > 5:
          print("Between 6 and 10")
      else:
          print("5 or less")
      
  6. Ternary operators and shorthand if-else in Python:

    • Description: Use the ternary operator for concise if-else statements.
    • Code:
      x = 10
      result = "Greater than 5" if x > 5 else "5 or less"
      print(result)
      
  7. Error handling and if-else in Python:

    • Description: Use if-else for error handling to execute different code blocks based on whether an error occurs.
    • Code:
      try:
          # Some code that may raise an exception
      except SomeError:
          print("Error occurred")
      else:
          print("No error occurred")
      
  8. Using if-else with list comprehensions in Python:

    • Description: Utilize if-else within list comprehensions to create conditional lists.
    • Code:
      numbers = [1, 2, 3, 4, 5]
      squared_numbers = [x**2 if x % 2 == 0 else x for x in numbers]
      print(squared_numbers)
      
  9. Switch-like behavior with if-else in Python:

    • Description: Simulate switch-like behavior using a series of if-else statements.
    • Code:
      def switch_case(value):
          if value == 1:
              return "Case 1"
          elif value == 2:
              return "Case 2"
          else:
              return "Default case"
      
  10. Optimizing code with efficient use of if-else:

    • Description: Optimize code by simplifying conditions and using if-else where appropriate.
    • Code:
      x = 10
      result = "Even" if x % 2 == 0 else "Odd"
      print(result)