Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

The “If” & “Nested If” Statements

1. The “If” Statement:

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops. An
"if statement" is written by using the if keyword.

Example:

Task: Age Eligibility

Write a Python program that checks if a person is eligible to vote based on their age. If the
person is 18 years or older, the program should print "You are eligible to vote." If the person is
younger than 18, it should print "You are not eligible to vote."

age = int(input("Enter your age: "))

if age >= 18:

print("You are eligible to vote.")

else:

print("You are not eligible to vote.")


In this task, we use a simple if statement to check if the age is greater than or equal to 18. If the
condition is true, it prints a message indicating eligibility to vote; otherwise, it prints a message
indicating ineligibility.

2. “Nested If” Statement:

Nested if statements are a way to create conditional logic with multiple levels of conditions. They are
structured by placing one if statement inside another. Here's a simple example in pseudocode:

Pseudocode:

if condition1:
if condition2:
# Code to execute when both conditions are true
else:
# Code to execute when condition1 is true but condition2 is false
else:
# Code to execute when condition1 is false

This allows you to create more complex decision trees in your code by checking multiple conditions in a
hierarchical manner. However, it's essential to keep nested if statements clear and well-indented to
maintain code readability.

Example 1:

x = 10
y=5

if x > 5:

print("x is greater than 5")

if y > 2:

print("y is also greater than 2")


else:

print("y is not greater than 2")

else:

print("x is not greater than 5")

print("This is outside the nested if statements")

In this example, we have two nested if statements. First, it checks if x is greater than 5. If that's true, it
goes into the inner if statement to check if y is greater than 2. Depending on the values of x and y,
different print statements will be executed. Finally, there's a statement outside the nested if statements
that will always be executed.

Example 2:
age = 25
income = 45000

if age >= 18:


print("You are of legal age.")

if income >= 30000:


print("You have a decent income.")
else:
print("You have a lower income.")

else:
print("You are underage.")

print("Thank you for using this program.")

In this example, it first checks if the person's age is 18 or older. If that's true, it proceeds to check
their income. Depending on age and income, different messages will be printed. The program
then concludes with a common message.
Example 3:

Task: Pizza Order

Write a Python program that takes an order for a pizza. The program should ask the user for the
size of the pizza and whether they want any extra toppings. The price of the pizza is based on the
size and toppings as follows:

 Small pizza (8 inches) costs $10.


 Medium pizza (12 inches) costs $15.
 Large pizza (16 inches) costs $20.
 Each topping costs an additional $2.

Ask the user for their pizza size and whether they want extra toppings. Then, calculate and print
the total price of the pizza.

pizza_size = input("Enter the size of the pizza (Small, Medium, Large):


").lower()
toppings = input("Do you want extra toppings? (yes/no): ").lower()

if pizza_size == "small":
pizza_price = 10
if toppings == "yes":
pizza_price += 2
elif pizza_size == "medium":
pizza_price = 15
if toppings == "yes":
pizza_price += 2
elif pizza_size == "large":
pizza_price = 20
if toppings == "yes":
pizza_price += 2
else:
pizza_price = 0 # Invalid size

if pizza_price > 0:
print(f"Total price for your pizza: ${pizza_price:.2f}")
else:
print("Invalid pizza size entered.")

This program uses two levels of nested if statements to determine the total price of a pizza based
on the size and whether the user wants extra toppings. It also handles cases of invalid input.

Example 4:

Task: Mobile Phone Purchase

Write a Python program that helps a customer purchase a mobile phone. The program should ask
the user for their budget and their preferences for certain features. The available mobile phones
are categorized as follows:

1. Budget Phones: $100 - $299


2. Mid-Range Phones: $300 - $599
3. High-End Phones: $600 and above

The program should consider the user's budget and preferences for camera quality and brand to
recommend a phone within their budget.

budget = float(input("Enter your budget for a mobile phone: $"))


camera_quality = input("Do you want a phone with a good camera? (yes/no):
").lower()
preferred_brand = input("Do you have a preferred brand? (e.g., Apple, Samsung,
Google): ").lower()

recommendation = ""

if budget >= 100 and budget <= 299:


if camera_quality == "yes" and preferred_brand == "google":
recommendation = "Google Pixel 4a"
elif camera_quality == "yes":
recommendation = "Samsung Galaxy A22"
else:
recommendation = "Nokia 2.4"
elif budget >= 300 and budget <= 599:
if camera_quality == "yes" and preferred_brand == "apple":
recommendation = "iPhone SE"
elif camera_quality == "yes":
recommendation = "OnePlus Nord N200"
else:
recommendation = "Moto G Power"
else:
recommendation = "Samsung Galaxy S21 Ultra"

if recommendation:
print(f"We recommend the {recommendation} for you.")
else:
print("Sorry, we couldn't find a suitable phone within your budget and
preferences.")

This program considers the user's budget, camera preference, and brand preference to
recommend a mobile phone within their budget range. It uses two levels of nested if statements
to make the recommendation.

Example 5:

Task: Grade Calculator

Write a Python program that calculates a student's letter grade based on their numerical score for
a course. The grading scale is as follows:

A: 90-100

B: 80-89

C: 70-79

D: 60-69

F: 0-59
Additionally, if a student's score is above 100 or below 0, print an error message. Ask the user to
input their score and then output their corresponding letter grade or an error message.

score = float(input("Enter your numerical score: "))

if score < 0 or score > 100:


grade = "Error: Invalid score entered"
else:
if 90 <= score <= 100:
grade = "A"
elif 80 <= score < 90:
grade = "B"
elif 70 <= score < 80:
grade = "C"
elif 60 <= score < 70:
grade = "D"
else:
grade = "F"

print(f"Your letter grade is: {grade}")

This program takes a numerical score as input and calculates the corresponding letter grade
based on a complex set of conditions. If the score is outside the valid range, it provides an error
message.

You might also like