Nested Conditionals
A nested conditional is a conditional that is inside the block of another conditional. For example:
materialCovered = True
IStudied = True
if materialCovered:
if IStudied:
print("We covered the material and I know it")
else:
print("We covered the material but I don't know it")
else:
print("We haven't covered the material yet")
# Prints: We covered the material and I know it
When using nested conditionals, it's important to pay attention to indentation. You can remember that a more indented block of code always follows a colon.
Nested conditionals can often be rewritten as chained conditions using logical operators. Our example can be rewritten as follows:
materialCovered = True
IStudied = True
if materialCovered and IStudied:
print("We covered the material and I know it")
elif materialCovered and not IStudied:
print("We covered the material but I don't know it")
else:
print("We haven't covered the material yet")
# Prints: We covered the material and I know it
It's good to realize that neither way is "wrong". In different situations, one way might seem more logical to you, so feel free to use it.
Instructions
We need the program to print Passed with distinction
if a student has 75 or more points, Passed
if they have 50 or more points. Otherwise, it should print Failed
. On line 4, insert a nested if points >= 75:
that prints Passed with distinction
if true. If not true (else
), it prints Passed
.
Start programming for free
9/10