Python Nested if else Statement Examples

Spread the love

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.

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.")

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:

  • If num is greater than 0, check if num is even by checking if the remainder when num is divided by 2 is 0.
    • If the remainder is 0, execute the code block that prints the message “The number is positive and even.”
    • If the remainder is not 0, execute the code block that prints the message “The number is positive but odd.”
  • If num is not greater than 0, execute the code block that prints the message “The number is not positive.”

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.")

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.")

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.")

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.")

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.

  • It can make the code hard to read and understand.
  • It can lead to errors and bugs if not properly implemented.
  • It can be difficult to maintain and modify as the code grows and evolves.
  • It can lead to code redundancy and duplication, which can affect performance.
  • It can limit the flexibility and scalability of the code.

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!

AlixaProDev

I am a software Engineer with extensive 4+ years of experience in Programming related content Creation.

Leave a Reply

You are currently viewing Python Nested if else Statement Examples