Welcome to our comprehensive guide on Nested If Statements in Python! In this lesson, we'll dive deep into understanding this powerful tool that will help you write more complex and efficient code. Let's get started!
If statements are the foundation of conditional logic in Python. They allow you to execute a block of code only when a certain condition is met.
if condition:
# Code block to execute if condition is TrueNow, what happens when we want to check multiple conditions or create more complex logic? That's where Nested If Statements come in handy. They allow you to create multiple levels of conditional logic.
if condition1:
# Code block for condition1
if condition2:
# Code block for condition2
...
else:
# Code block for when condition2 is False
else:
# Code block for when condition1 is FalseLet's break this down:
condition1 is checked first. If it's True, the code within the first indented block is executed.condition1 is True, condition2 is checked. If it's True, the code within the second indented block is executed. If condition2 is False, the code within the else block for the second if statement is executed.if statements as needed.condition1 is False, the code within the else block for the first if statement is executed.Let's put this into practice with an example. We'll create a simple age checker that restricts access to a website based on age.
age = int(input("Enter your age: "))
if age >= 18:
print("Access granted!")
if age >= 25:
print("You are eligible for our special promotion.")
else:
print("You can access the general content.")
else:
print("Sorry, you're too young to access this website.")Try running this code! When you input your age, it will check if you're over 18. If so, it will check if you're over 25, and provide different messages accordingly.
What does a nested if statement do in Python?
That's all for now! In the next lesson, we'll delve deeper into more advanced applications of nested if statements. Happy coding! 🤖🎉