Explanation of if elif else Statement Example Usage in python

  • 2021-12-05 06:54:26
  • OfStack

1. Judge the statement of multiple conditions. If if is true, execute the statement after if.

2. If elif is true, elif is executed, and the following code blocks are not executed.

3. If if and elif are not satisfied, execute else statement.

Instances


if expression:
    statements...
elif expression:
    statements...
     #  There can be 1 Strip or strips elif Statement 
else:
    statement...

Expansion of knowledge points:

Sometimes, an if … else … is not enough. For example, according to the age division:

Condition 1: 18 years old or above: adult
Condition 2: 6 years old or above: teenager
Condition 3: Under 6 years old: kid

Python if-elif-else Knowledge Points


if age >= 18:
  print 'adult'
else:
  if age >= 6:
    print 'teenager'
  else:
    print 'kid'

Writing this way, we get a two-tiered nested if … else … statement. There is no problem with this logic, but if you continue to add conditions, such as baby under 3 years old:


if age >= 18:
  print 'adult'
else:
  if age >= 6:
    print 'teenager'
  else:
    if age >= 3:
      print 'kid'
    else:
      print 'baby'

This indentation will only get more and more, and the code will get uglier and uglier.

To avoid nested if … else … we can use if … multiple elif … else … to write all the rules at once:


if age >= 18:
  print 'adult'
elif age >= 6:
  print 'teenager'
elif age >= 3:
  print 'kid'
else:
  print 'baby'

elif means else if. In this way, we have written a series of conditional judgments with very clear structure.

Special attention: This series of conditional judgments will be judged in turn from top to bottom. If a judgment is True, the corresponding code block will be executed, and the subsequent conditional judgments will be ignored directly and no longer executed.

Consider the following code:


age = 8
if age >= 6:
  print 'teenager'
elif age >= 18:
  print 'adult'
else:
  print 'kid'

When age = 8, the result is correct, but when age = 20, why is adult not printed?

If you want to repair it, how should you repair it?

Mission

If the results are defined according to scores:

90 points or above: excellent

80 or above: good

60 points or above: passed

Under 60 points: failed

Please write a program to print the results according to the scores.

Answer

score = 85

if score > = 90:
print 'excellent'
elif score > = 80:
print 'good'
elif score > = 60:
print 'passed'
else :
print 'failed'


Related articles: