October 13, 2024

Python If-Else Statements

Python If-Else Statements

The if-else statement in Python allows you to execute certain blocks of code based on specific conditions. This control structure is fundamental for decision-making in Python programs.

Syntax of If-Else Statements

python

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

How the If-Else Statement Works

  1. Condition Evaluation:
    • The if statement evaluates a condition (a Boolean expression that results in either True or False).
  2. True Condition:
    • If the condition evaluates to True, the block of code immediately under the if statement is executed.
  3. False Condition:
    • If the condition evaluates to False, the block of code under the else statement (if provided) is executed.

Example of If-Else Statement

Here’s a simple example that checks whether a number is positive or negative:

number = int(input("Enter a number: "))
if number >= 0:
print("The number is positive or zero.")
else:
print("The number is negative.")

Flow of Execution

  1. Input: The user inputs a number.
  2. Condition Check: The program checks if the number is greater than or equal to zero.
    • If True, it prints “The number is positive or zero.”
    • If False, it prints “The number is negative.”

Multiple Conditions with Elif

You can extend the if-else structure using elif (short for “else if”) to check multiple conditions.

Syntax of If-Elif-Else

if condition1:
# Block of code to execute if condition1 is True
elif condition2:
# Block of code to execute if condition2 is True
else:
# Block of code to execute if both condition1 and condition2 are False

Example of If-Elif-Elsenumber = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number == 0:
print("The number is zero.")
else:
print("The number is negative.")

Key Points

  • The if-else structure is crucial for controlling the flow of a Python program.
  • You can have multiple elif branches between an if and an else.
  • The blocks of code inside if, elif, and else statements must be indented.

Using if-else statements allows for more dynamic and responsive Python programs that can handle various input scenarios and make decisions based on conditions.