Conditional handling

Conditional handling

Conditional handling in Python involves using if, else, and optionally elif (short for "else if") statements to control the flow of a program based on certain conditions. Here are some examples to illustrate the usage:

1. Simple if Statement:

# Example 1: Simple if statement
x = 10

if x > 5:
    print("x is greater than 5")

Output:

x is greater than 5

In this example, the code checks if the value of x is greater than 5. If the condition is true, the indented block of code under the if statement is executed.

2. if-else Statement:

# Example 2: if-else statement
y = 3

if y % 2 == 0:
    print("y is even")
else:
    print("y is odd")

Output:

y is odd

Here, the code checks if y is an even number. If true, it prints "y is even"; otherwise, it prints "y is odd" using the else block.

3. if-elif-else Statement:

# Example 3: if-elif-else statement
grade = 75

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
else:
    print("Fail")

Output:

C

This example demonstrates the use of if, elif, and else to determine a student's grade based on the numerical value. The conditions are checked in order, and the first true condition's block is executed.

These examples showcase the basic structure of conditional statements in Python. Keep in mind that indentation is crucial in Python; it indicates the scope of the code blocks. Also, conditions are evaluated in order, so the order of if, elif, and else statements matters. Once a true condition is found, the corresponding block is executed, and the remaining conditions are skipped.

Outro

In the next article in this blog series, we will look into Lists and Tuples.

Stay tuned.