How to Use if-else Statements in Python?

The if-else statement in Python is a fundamental control structure that allows you to execute code based on certain conditions. It’s essential for decision-making in your programs.

Basic Syntax

if condition:
    # Code to execute if condition is true
else:
    # Code to execute if condition is false

Example

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

Using elif for Multiple Conditions

The elif keyword allows you to check multiple conditions:

score = 85
if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
elif score >= 70:
    print("Grade C")
else:
    print("Grade D")

Nesting if Statements

You can nest if statements within each other:

num = 10
if num > 0:
    print("Positive number")
    if num % 2 == 0:
        print("Even number")
    else:
        print("Odd number")
else:
    print("Negative number")

Conditional Expressions (Ternary Operator)

Python supports conditional expressions for simple if-else statements:

message = "Even" if num % 2 == 0 else "Odd"
print(message)

Conclusion

Understanding if-else statements is crucial for controlling the flow of your Python programs. They allow you to make decisions and execute code conditionally.

Leave a Reply

Your email address will not be published. Required fields are marked *