Nested if statements #
In Python, it's possible to have an if statement inside another if statement. This is known as a nested if statement.
A nested if statement can be useful when you want to check multiple conditions before deciding what code to run. For example, you may want to check if a number is greater than 5 and less than 10. You could do this with a single if statement, but some developers prefer to use a nested if statement:
x = 7
if x > 5:
if x < 10:
print("x is between 5 and 10")
In this example, the outer if statement checks if x is greater than 5. If it is, the inner if statement checks if x is less than 10. If both conditions are true, the string "x is between 5 and 10" is printed.
It's important to remember that each if statement needs to be indented properly. In the example above, the inner if statement is indented further, because it's inside the outer if statement.
Exercise #
Rewrite the if statement inside the function get_discount() so that the function does the following:
- If
employeeisTrueandyearsis more than 5, returns 20. - If
employeeisTrueandyearsis less than or equal to 5, returns 10. - if
employeeisFalse, returns 5.
Tests #
get_discount(employee=True, years=10)should return20{: #test-1 }get_discount(employee=True, years=5)should return10{: #test-2 }get_discount(employee=True, years=1)should return10{: #test-3 }get_discount(employee=False)should return10{: #test-4 }- Use nested
ifinstead of usingandkeyword {: #test-5 }
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules