Python Nested If Statements

The python if-then-else statement runs a block of code based on the condition which can be true or false. Sometimes you need to check multiple conditions event after a block is true. This is achieved using python nested if statements.

For example, assume that a user is trying to login to a system. This can be easily implemented using a single if-then-else statement.

First, we check the username and then check the password and allow user to login to the system. Consider the following python code.

username = input("Enter Username: ")
password = input("Enter Password: ")

# Now we check the username and password and print success else failure
if username == "Donald" and password == "[email protected]":
       print("Success")
else:
       print("Failure")

Note that the program does the job, but in case the password or username is wrong, it does not tell you anything and prints "Failure" only.

Therefore, to solve problem like this we can use a nested if statement or if-then-else or any such constructs.

Consider the modified code below.

username = input("Enter Username: ")
password = input("Enter Password: ")

# check the username first 

if username == "Robin":
      # Check password now
      if password == "test#1212":
           print("Login Successful")
      else:
           print("Password Incorrect! try again!")
else:
     # print the failure message for username
      print("Invalid User")

The code above will be able to tell us the reason for failure. it may be username or password, but we will know.

The nested if-then-else can even be possible in elif or else block.

customerName = "Peter"
name = input("Enter customer name: ")
cardType = "Visa"
password = "[email protected]"
attempt = 3

for i in range(attempt):
    # Withdraw the money from ATM
    if customerName == name:
          print("Customer verified")
          if cardType == "Visa":
              print("Card verified")
              if password == "[email protected]":
                   print("Withdraw Cash Now")
              else:
                   print("Incorrect Password")
          else:
              print("Invalid Card")
    else:
    
         print("Invalid Customer")
         
         if i >= 2:
             print("Try again later!")
         else:
             print("Try again!")
             name = input("Enter customer name:")

The output of the program is as follows.

=========== RESTART: C:/Python_projects/Customer_ATM_Nested_IF.py ===========
Enter customer name: Kiran
Invalid Customer
Try again!
Enter customer name:Larson
Invalid Customer
Try again!
Enter customer name:Romeo
Invalid Customer
Try again later!
Skip to content