Built with Tutify.io

    AIStudyLabs

    Python Nested if else Statement Examples

    Python Nested if else Statement Examples

    Let's learn nested "if else" statements in Python and how they can be used to test multiple conditions. In Python programming, sometimes you need to check multiple conditions before making a decision. That's where nested if-else statements come in.

    <a id="h-1-quick-examples-of-python-nested-if-else"></a>

    1. Quick Examples of Python Nested "if else"

    These examples will give you a high-level overview of how nested if-else statements work, which we will discuss in more detail later on.

    
    # Example 1 : Number checker
    num = 5
    
    if num > 0:
        print("The number is positive.")
    else:
        if num < 0:
            print("The number is negative.")
        else:
            print("The number is zero.")
    
    # Example 2 : Age classifier
    age = 35
    
    if age >= 60:
        print("You are a senior citizen.")
    else:
        if age >= 18:
            print("You are an adult.")
        else:
            print("You are a teenager.")
    

    <a id="h-2-syntax-of-nested-if-else"></a>

    2. Syntax of Nested "if else"

    Nested if-else statements in Python allow you to test multiple conditions and execute different code blocks based on the results of these tests. The basic syntax of a nested if-else statement is as follows: (Using if-else statement within another if statement.

    
    # Syntax of nested if else
    if condition1:
        # Execute if condition1 is true
        if condition2:
            # Execute if both condition1 and condition2 are true
        else:
            # Execute if condition1 is true but condition2 is false
    else:
        # Execute if condition1 is false
    

    As you can see, the syntax of a nested if-else statement is very similar to that of a regular if-else statement, except that it includes one or more additional if-else statements within the code blocks.

    Let's have an example of Python nested "if else". consider the following scenario:

    Now we can implement this case scenario with Python nested if else statement:

    
    # Simpler example of a nested if-else statement
    num = 10
    
    if num > 0:
        if num % 2 == 0:
            print("The number is positive and even.")
        else:
            print("The number is positive but odd.")
    else:
        print("The number is not positive.")
    

    <a id="h-3-nested-if-else-with-elif"></a>

    3. Nested "if else" with "elif"

    We can make use of Nested "if else" along with "elif" Statement. This can give us more power over conditional handling. We can create much stronger and more complex logic using these three statements.

    See the below example. The example shows how nested if-else statements can be used to make complex decisions in programming.

    
    # Password and Username Checking
    username = input("Enter your username: ")
    password = input("Enter your password: ")
    
    if username == "admin":
        if password == "password":
            print("Login successful! Welcome, admin.")
        elif password == "12345":
            print("Weak password. Please reset your password.")
        else:
            print("Incorrect password. Please try again.")
    else:
        if username == "guest":
            if password == "guest":
                print("Login successful! Welcome, guest.")
            else:
                print("Incorrect password. Please try again.")
        else:
            print("Unknown user. Please try again.")
    

    <a id="h-4-nested-if-else-for-validation"></a>

    4. Nested "if else" for Validation

    When you're building a form or taking user input in your application, you need to validate the data to ensure it's in the expected format. A common way of doing this is by using nested if-else statements to check each field for errors.

    For example, you might check if an email address is valid by first checking if it's not empty, then checking if it contains an "@" symbol, and finally checking if it ends with a valid domain name.

    
    # Using if-else for Validation
    name = input("Enter your name: ")
    email = input("Enter your email address: ")
    password = input("Enter your password: ")
    
    if name == "":
        print("Name cannot be empty.")
    else:
        if "@" not in email:
            print("Invalid email address.")
        else:
            if len(password) > 8:
                print("Password must be at least 8 characters long.")
            else:
                print("Registration successful.")
    

    <a id="h-5-nested-if-else-for-authentication"></a>

    5. Nested "if-else" for Authentication

    Let's say you're building a simple login system that requires users to enter their username and password. You might use nested if-else statements to authenticate the user and authorize their access.

    
    # Using if-else for Authentication
    username = input("Enter your username: ")
    password = input("Enter your password: ")
    
    if username == "admin":
        if password == "password123":
            print("Login successful.")
        else:
            print("Invalid password.")
    else:
        print("Invalid username.")
    

    <a id="h-6-side-effects-of-nested-if-else"></a>

    6. Side Effects of Nested if else

    While Nested "if else" can be useful, there are several reasons why you should stop overusing nested if-else statements in your code.

    <a id="h-7-summary-and-conclusion"></a>

    7. Summary and Conclusion

    We have covered the basics of python nested if-else statements and provided examples of their use in real-world scenarios. While Nestd if else is a good way to handle complex programming logic, it also has a downside which we have discussed. Let me know if you have any questions.

    Happy Coding!

    <a id="h-related-articles"></a>

    Related Articles