Elif Python with examples

The elif statement allows you to test multiple expressions and run a piece of code when one of the conditions is true. The elif statement, like else, is optional. In contrast to other statements, which can only have one, an if can have an arbitrary amount of elif statements following it.

Elif statement in Python

The syntax of the Elif statement is as follows:

if first_expression:
   statement(s)
elif second_expression:
   statement(s)
elif third_expression:
   statement(s)
else:
   statement(s)

The elif statement also works with an ‘else’ statement that can be used in conjunction with an if statement. When the conditional expression present in the prevalent if statement resolves to 0 or FALSE, the else statement executes a block of code. The else statement is optional, and there can only be one other statement after the if statement.

The ‘if…else’ statement’s syntax is as follows:

if expression:
   statement(s)
else:
   statement(s)

What is the original Structure of Statements?

Statements in any Python script are executed sequentially from the first to the last by default. The sequential flow can be changed in two ways if the processing logic warrants it:

Python’s ‘if’ keyword is used to implement decision control. Following the ‘if’ keyword is any Boolean statement that evaluates to True or False. To begin a block with an increased indent, use the: sign followed by Enter. If the Boolean expression evaluates True, one or more sentences with the same indent level will be performed.

Reduce the indentation to finish the block. Following statements will be executed outside of the if condition. The ‘if’ condition is demonstrated in the following example.

Example: The if Block contains a single statements

item_cost = 190

if item_cost < 200:
    print("The item's cost price is below 200")

Because the expression price 100 evaluates True in the preceding example, the block will be executed. The if block begins on a new line, and all statements within the if condition begins with an increased indentation, either a space or a tab. The if block above has simply one sentence. The if condition in the following example contains numerous statements.

Example: The if Block contains multiple statements

item_cost  = 60
number_of_items = 7
if item_cost *quantity > 300:
    print("item_cost *number_of_items is above than 300")
    print("item cost  = ", item_cost )
    print("number of items = ", number_of_items)

The if condition above contains several sentences with the same indentation. If all statements are not in the same indentation, either space or tab, an IdentationError will be raised. For example, try out the following code.

item_cost  = 60
number_of_items = 7
if item_cost *quantity > 300:
    print("item_cost *number_of_items is above than 300")
     print("item cost  = ", item_cost )
      print("number of items = ", number_of_items)

Statements with the same indentation level as the ‘if’ condition is ignored in the if block. In fact, they will think about getting out of the if predicament.

Example: Statements out of Block

item_cost  = 60
number_of_items = 7
if item_cost *quantity > 300:
    print("item_cost *number_of_items is above than 300")
    print("item cost  = ", item_cost )
print("number of items = ", number_of_items)

The following example shows several ‘if’ conditions.

Example: Demonstration of Many ‘if’ Conditions

item_cost = 32

if item_cost < 50:
 print("item_cost is smaller than 50")

if price == 50:
  print("item_cost is 50")

if item_cost >50:
    print("item_cost is more than 50")

Each ‘if’ block has a statement in a different indentation, which is correct because they are distinct from one another. For your information, the default indentation level should be four spaces or a tab for improved readability.

Example: if ..else statement

math_score = 100
if math_score ==100:
   print("1 – Excellent Performance")
   print(math_score)
else:
   print("1 – Average Performance")
   print(math_score)

math_score = 0
if math_score ==0:
   print("2 – Bad Performance")
   print(math_score)
else:
   print("2 – Uknown Performance")
   print(math_score)

print "Well Done!"

The vital thing to note is that before even using if … else or elif, you first must understand how the if statement works as a standalone statement. Below is the syntax to help you put this into perspective.

if test expression:
    statement(s)

In this case, the program analyzes the test expression and executes the statement(s) only if the test expression is True. The statement(s) are not executed if the test expression is False.

The indentation in Python indicates the content of the if statement. The body begins with an indentation and ends with the first unintended line. As a matter of fact, Python considers non-zero numbers to be True. Additionally, None and 0 are considered False.

Core Python does not include a switch or case statements like other languages. However, we may emulate switch cases with if…elif…statements, as shown below.

math_score = 100
if math_score == 100:
   print("1 – Excellent performance")
   print(math_score)
elif math_score == 80:
   print("2 – Good Performance")
   print(math_score)
elif math_score == 60:
   print("3 – Average Performance")
   print(math_score)
else:
   print("4 – Below Par Performance")
   print(math_score)

print "Math Results Done!"

Nested if statements in Python

An if…elif…else statement can be contained within another if…elif…else statement. In computer programming, this is known as nesting. These statements can be nested within one another indefinitely. The only way to determine the depth of nesting is by indentation. They can be perplexing, so they should be avoided unless absolutely necessary.

Below, we look at an example of using the nested if statements in Python.

def check_if_number_is_positive_or_negative():

	'''
	In this program, we input a number, determine whether it is positive, negative, or zero, and show an appropriate message. This time, we're going to use a nested if statement.

	'''

	var_num = float(input("Please input a number: "))
	if var_num >= 0:
    		if var_num == 0:
        			print("This is a zero")
    		else:
        			print("This is a positive number")
	else:
    		print("This is a negative number")

print("Expected: This is a zero, Actual:",check_if_number_is_positive_or_negative() ) # var_num = 0
print("Expected: This is a negative number, Actual:", check_if_number_is_positive_or_negative())# var_num =-8.3
print("Expected: This is a positive number, Actual: ", check_if_number_is_positive_or_negative())# var_num=7.9

Example: Checking if a given number is either Negative or Positive

def check_positive_negative(var_num)

	'''
	In this application, we determine whether the number is positive,
	negative, or zero and display the relevant message.

	'''

	

	# Try these two variations as well:
	# var_num = 0
	# var_num = -9.5

	if var_num > 0:
    		print(var_num, " is a positive number")
	elif num == 0:
    		print(var_num, "is a zero")
	else:
    		print(var_num, "is a negative number")

print("Expected Value: is a positive number, Actual: ", check_positive_negative(98.6))
print("Expected Value: is a zero, Actual: ", check_positive_negative(0))
print("Expected Value: is a negative number, Actual: ", check_positive_negative(-9.5))

Upon running the code snippet above, ‘is a positive number’ is printed when variable var_num is positive. However, if var_num is equal to zero, the value ‘is zero’ is displayed as the output. Additionally, ‘is a negative number’ is printed if var_num is negative.

Example: Using if, elif, nested & else Conditions

item_cost = 60
no_of_items = 6
total_cost = item_cost*no_of_items

if total_cost> 121:
    if total_cost > 500:
        print(" total_cost is greater than 500")
    else:
        if total_cost < 500 and amount > 400:
            print(" total_cost is")
        elif total_cost < 500 and total_cost > 300:
            print(" total_cost is between 300 and 500")
        else:
            print(" total_cost is between 200 and 500")
elif total_cost == 100:
    print("total_cost is 100")
else:
    print("total_cost is less than 100")

Conclusion

Elif is an abbreviation for else if. It enables us to search for numerous expressions. If the condition for if is False, the condition of the next elif block is checked, and so on. However, if all of the conditions are False, the ‘else’ body is executed.

According to the condition, just one of the numerous if…elif…else blocks is executed. There can only be one other else block in the if block. However, it is possible to have numerous elif blocks.

Also, remember that when we wish to execute code only if a given condition is met, we must make a decision. Python’s if…elif…else statement is pivotal in making decisions.

Similar Posts

Leave a Reply

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