A nested if statement refers to placing one if statement inside another. This allows for more complex decision-making, where the outcome of one condition depends on the result of a prior condition. It is a fundamental technique to control the flow of execution in your program. Table of Contents What is a Nested If Statement? Syntax of Nested If Statement Example of Nested If Statement How Nested If Works Use Cases for Nested If Avoiding Overuse of Nested If Common Pitfalls with Nested If Mini-Project: Grading System Interview Questions and Answers (Google, Amazon, TCS, Infosys, Zoho) 1. What is a Nested If Statement? A nested if statement occurs when you place an if statement inside another if statement. This is useful when you need to evaluate multiple conditions that depend on each other. The structure of a nested if can be simple or complex, depending on how many layers of conditions you have. Each if statement is evaluated sequentially, and the inner if is only checked if the outer if is true. 2. Syntax of Nested If Statement The syntax for a nested if statement is similar to the regular if statement but with one if inside another. if condition1: if condition2: # Code to execute if both conditions are True else: # Code to execute if condition2 is Falseelse: # Code to execute if condition1 is False condition1: The outer condition that is checked first. condition2: The inner condition that is checked only if the outer condition is True. Example: age = 20 has_ticket = True if age >= 18: if has_ticket: print("You can enter the movie.") else: print("You cannot enter without a ticket.") else: print("You are too young to enter the movie.") In this case: The first if checks if the person is old enough to enter the movie. If true, it checks if they have a ticket (the nested if). If any condition fails, it will print a corresponding message. 3. Example of Nested If Statement Let’s look at a simple example to illustrate the behavior of a nested if statement. = 10 y = 20 if x > 5: if y < 30: print("Both conditions are True.") else: print("Second condition is False.") else: print("First condition is False.") Output: Both conditions are True. Here: The first if checks if x > 5, which is true. The nested if checks if y < 30, which is also true, so it prints "Both conditions are True.". 4. How Nested If Works When using nested if statements: The program first checks the outermost if condition. If the outer condition is True, the program will move to the next inner if statement. If the outer condition is False, the program will skip the nested if and execute the else block if present. This creates a chain of logical checks, where each subsequent condition is only checked if all the prior conditions are met. 5. Use Cases for Nested If Nested if statements are often used when: You have multiple conditions that depend on each other. One condition must be true before evaluating another. You need to handle more specific cases under general conditions. Examples: Grading system (check if the score is high enough to pass, then check for honors). User access control (check user authentication, then check user roles). Order processing (check if the payment is successful, then check stock availability). 6. Avoiding Overuse of Nested If While nested if statements can be useful, overusing them can lead to complex and hard-to-read code. To avoid excessive nesting: Break down complex logic into separate functions. Use elif for handling multiple conditions. Consider using logical operators like and, or to combine conditions in a single if block. 7. Common Pitfalls with Nested If Deep Nesting: Too many nested levels can make the code hard to understand and maintain. Missing else for inner conditions: Ensure you handle all possible cases, especially when inner if conditions can lead to unexpected behavior. Indentation Errors: Python relies on indentation to identify blocks of code. Ensure your if and nested if blocks are properly indented. 8. Mini-Project: Grading System Let’s create a simple grading system that assigns a grade based on the score. The system checks if the score is valid (between 0 and 100) and then assigns a grade. Objective: The program will ask for a score. It will first check if the score is between 0 and 100. Then, it will assign a grade based on the score: A (90 and above) B (80-89) C (70-79) D (60-69) F (below 60) def grade_student(): score = int(input("Enter your score: ")) if score >= 0 and score <= 100: if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F") else: print("Invalid score. Please enter a value between 0 and 100.") grade_student() Sample Output: Enter your score: 85Grade: B Here: The program first checks if the score is valid. Then, it assigns the appropriate grade based on the score. Interview Questions and Answers Google Q: What is the output of the following code? x = 5 y = 10 if x == 5: if y == 10: print("Both conditions are true.") else: print("Only x is true.") else: print("x is not 5.") A: The output will be "Both conditions are true.". Amazon Q: How would you handle a decision where you check multiple conditions in sequence? A: Use nested if statements. For example, check if a person is an adult, and then check if they have a voter ID to determine if they can vote. TCS Q: Can you give an example where a nested if is useful in real-world applications? A: A nested if is useful in scenarios like user login systems. First, check if the user exists, then check if the password is correct, etc. Infosys Q: What is the difference between an if-else and a nested if statement? A: An if-else statement checks one condition, while a nested if allows you to check additional conditions after the first condition is met. Zoho Q: How do you avoid deep nesting in if statements? A: To avoid deep nesting, break the logic into smaller functions or use logical operators like and, or to combine conditions in a single if statement. Conclusion Nested if statements are a powerful tool for making decisions based on multiple conditions. They help you handle complex decision-making logic where one condition depends on the result of another. However, be mindful of overusing them, as too many nested levels can make your code difficult to read and maintain. By using proper indentation and logical operators, you can keep your code clean and efficient. [quiz-cat id="17226"]