Sunday 18 August 2024

Python Nested If Examples

Nested-If Statements in Python

When we write if statements inside another if statement, it is called Nested If Statements. These can be very useful to make complex decisions in your program. They can be several levels deep. They are also a type of decision making statement in python. 

Followings are some popular examples related to usage of the python nested-if statements.

Example 1: Python program to print student's grade.

# Python program to print student's grade

score = int(input("Enter your marks:"))

if score >= 90:
    grade = 'A'
else:
    if score >= 80:
        grade = 'B'
    else:
        if score >= 70:
            grade = 'C'
        else:
            grade = 'F'

print("Grade:", grade)


Output

Enter your marks:85 Grade: B


Example 2: Python program to check weather conditions. 

# Checking Weather Conditions
temperature = 30
raining = False

if temperature > 25:
    if raining:
        print("It's warm but raining. Bring an umbrella!")
    else:
        print("It's warm and sunny. Enjoy the weather!")
else:
    if raining:
        print("It's cold and raining. Better stay indoors!")
    else:
        print("It's cold but dry. Dress warmly!")

Output

It's warm and sunny. Enjoy the weather!


Example 3: Python program to check user authentication (username and password).
 
# User Authentication
username = "admin"
password = "12345"

if username == "admin":
    if password == "12345":
        print("Access granted")
    else:
        print("Incorrect password")
else:
    print("Username not found")

Output
Access granted


Example 4: Python program to check eligibility for a loan based on given Age and Income.

# We assume that a person is eligible for loan if age is
# above 18 years and income greater than or equal to 40000.

age = int(input("Enter your age in years:"))
income = int(input("Enter your income in Rs:"))

if age > 18:
    if income > 40000:
        print("You are eligible for the loan")
    else:
        print("You are not eligible for the loan due to low income")
else:
    print("You are not eligible for the loan due to age restriction")

Output
Enter your age in years:30 Enter your income in Rs:50000 You are eligible for the loan


Example 5:  Python program to check Positive, Negative or Zero number.

# Checking for Positive, Negative, or Zero Number
number = int(input("Enter one number:"))
if number >= 0:
    if number == 0:
        print("The number is zero")
    else:
        print("The number is positive")
else:
    print("The number is negative")

Output
Enter a number:5 The number is positive

* * *