Monday, August 25, 2025

🐍NESTED CONDITIONS

Nested Conditions in Python

Learn how to handle multiple layers of decisions using nested if statements.

Introduction

Nested conditions are if-else statements inside another if-else. They allow you to make decisions based on multiple conditions simultaneously.

Basic Nested Condition


age = 20
citizen = True

if age >= 18:
    if citizen:
        print("You can vote")
    else:
        print("You are not a citizen")
else:
    print("You cannot vote")

Output:


You can vote

Multiple Layers of Nesting

You can have several layers of nested if statements:


marks = 85

if marks >= 50:
    if marks >= 90:
        print("Grade: A+")
    elif marks >= 75:
        print("Grade: A")
    else:
        print("Grade: B")
else:
    print("Fail")

Output:


Grade: A

Common Mistakes

  • Wrong indentation:
    if age >= 18:
    if citizen:
        print("You can vote")
    IndentationError: expected an indented block
    ✅ Always indent nested blocks properly:
    if age >= 18:
        if citizen:
            print("You can vote")
  • Using capital keywords:
    If age >= 18:
        Print("You can vote")
    SyntaxError: invalid syntax
  • Missing colon:
    if age >= 18
        if citizen:
            print("You can vote")
    SyntaxError: expected ':'

💡 Try It Yourself

  1. Ask the user for age and citizenship, then print whether they can vote or not.
  2. Take a student's marks as input. Print "Pass" or "Fail". If passing, assign grades A+, A, B based on marks.
  3. Write a program to check if a number is positive, negative, or zero, and if positive, check if it is even or odd.

What’s Next?

Now that you understand nested conditions, we will move on to Practical Examples in Python. These examples will combine what you have learned so far: input, operators, and conditionals.

➡️ Next: Practical Examples of control flow

⬅️ Back to Main Page

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??