DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

An if statement can have as many elif conditions as you
want to add to the conditional check. Good coding
practices recommend simplification, but there is no real
limit to how many you add. Here is an example that uses
two elif conditionals:


Click here to view code image


>>> n = 3
>>> if n == 17:
... print('Number is 17')
... elif n < 10:
... print('Number is less than 10')
... elif n > 10:
... print('Number is greater than 10')
...
Number is less than 10

Since each if and elif statement does something only if
the condition identified is true, it may be helpful to have
a default condition that handles situations where none of
the if or elif statements are true. For this purpose, you
can assign a single else statement at the end, as shown
in Example 3-2.


Example 3-2 Adding a Final else Statement

Click here to view code image


score = int(input('What was your test
score?:'))
if score >= 90:
print('Grade is A')
elif score >= 80:
print('Grade is B')
elif score >= 70:
print('Grade is C')
elif score >= 60:
print('Grade is D')
else:
print('Grade is F')
What was your test score?:53
Free download pdf