Python elif keyword

Python elif keyword is used to provide an alternative course of action to take if the expression in an if statement turns out False.

The elif keyword plays a crucial role in constructing conditional statements that provide multiple choices and control flow based on different conditions.

Example 1: The syntax

The elif keyword is similar to else if in programming languages like Java.

It allows you to specify an additional condition to check if the preceding if or elif conditions are evaluated to False.

Here’s an example:

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

The elif keyword is used in conjunction with if and else to construct a chain of conditions.

Each condition is evaluated in order, and as soon as one of the conditions evaluates to  True, the corresponding block of code associated with that condition is executed.

Hence, the rest of the conditions are skipped.

Example 2: Using elif statements for grading scores

To understand the usage of the elif keyword, let’s consider a practical example.

Suppose we want to assign a grade to a student based on their test score.

You can use elif to evaluate different ranges of scores and assign the appropriate grade:

score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'F'

print("Grade:", grade)

Output:

Grade: B

In this example, the code evaluates the test score against different conditions using elif.

Once the first condition evaluates to True, the corresponding grade is assigned, and the remaining conditions are bypassed.

Example 3: Using elif statements to display colour inputs

In the example below,  elif statements are used to determine the colour entered by the user and as well display a message.

colour = input('enter a colour: ')
if colour == 'red':
    print('you entered a red colour')
elif colour == 'green':
    print('you entered a green colour')
elif colour == 'blue':
    print('you entered a blue colour')
else:
    print('you entered a colour')

Conclusion

The elif keyword in Python provides a powerful tool for constructing decision-making logic.

By understanding its syntax and best practices, you can create conditional statements that handle multiple scenarios effectively.

The ability to evaluate and branch code based on various conditions is crucial in building dynamic and intelligent applications.

 

Leave a Reply

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