0% found this document useful (0 votes)
24 views21 pages

Lecture - 2 2

Uploaded by

osesayjr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views21 pages

Lecture - 2 2

Uploaded by

osesayjr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Control_structures

Limkokwing University of Creative Technology

Lecture 2 and 3 : Decision Strutures


Prepared By Alpha Omar Leigh(Msc)

The objectives of this lecture are to:


1. Understand and apply if, else, and elif statements in Python.
2. Learn about boolean expressions and how they are used in decision-making.
3. Practice solving programming problems involving decision structures.
4. Gain proficiency in writing nested if statements for complex decision-making scenarios.
5. Provide examples, explanations, and exercises to reinforce understanding and skill development.
6. Support learners in improving problem-solving abilities and coding skills.
7. Foster active engagement and participation in discussions related to programming concepts and
problem-solving strategies.

Boolean Expressions and Relational Operators


Page 1 of 21
Control_structures
In programming, when we talk about the "if" statement, it's like asking a question: "Is this true or false?" To
answer this question, we use what are called Boolean expressions. These expressions are named after George
Boole, an English mathematician who, back in the 1800s, developed a system of math where we can deal with
true and false in computations.
Now, a Boolean expression typically involves a relational operator. What's that? Well, it's like a tool we use to
check if there's a certain relationship between two things. For instance, the ">" symbol checks if one thing is
greater than another, while "==" checks if two things are equal.
Definitions:
Boolean Expression: An expression that evaluates to either true or false.
Relational Operator : A symbol or sequence of symbols used in a programming language to determine
the relationship between two values.
Here's a table to help you understand these relational operators better:

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
⇐ Less than or equal to
== Equal to
!= Not equal to

Let's see some more examples to illustrate how these operators work:
Example 1:

x = 10
y=5
print(x > y) # Output: True
print(x < y) # Output: False

Example 2:

a=7
b=7
print(a >= b) # Output: True
print(a <= b) # Output: True

Example 3:

Page 2 of 21
Control_structures

name1 = "Vini"
name2 = "Jude"
print(name1 == name2) # Output: False
print(name1 != name2) # Output: True

Here's a table with more examples comparing variables x and y:

Expression Meaning
x>y Is x greater than y?
x<y Is x less than y?
x >= y Is x greater than or equal to y?
x⇐y Is x less than or equal to y?
x == y Is x equal to y?
x != y Is x not equal to y?

You can actually play around with these operators in Python. Just fire up the Python interpreter and type in your
expression. It will tell you whether it's true or false. Here's a quick example:

1. >>> length = 5
2. >>> width = 3
3. >>> length > width
4. True

Example 1: Checking if a number is even:

num = 6
print(num % 2 == 0) # Output: True

Example 2: Checking if a number is within a cer tain range:

value = 25
print(10 <= value <= 30) # Output: True

Example 3: Checking if a number is odd:

num = 7
print(num % 2 != 0) # Output: True

Example 4: Checking if a number is positive:

num = 10
print(num > 0) # Output: True

Example 5: Checking if a number is negative:

Page 3 of 21
Control_structures

num = -5
print(num < 0) # Output: True

Example 6: Checking if a number is zero:

num = 0
print(num == 0) # Output: True

Class Work
1. For each of the following conditional expressions, guess whether
they evaluate to True or False. Then type them into the interactive
window to check your answers:
1. 1 <= 1
2. 1 != 1
3. 1 != 2
4. "good" != "bad"
5. "good" != "Good"
6. 123 == "123"

2. For each of the following expressions, fill in the blank (indicated by


__) with an appropriate boolean comparator so that the expression
evaluates to True:
1. 3 __ 4
2. 10 __ 5
3. "jack" __ "jill"
4. 42 __ "42"

Logical Operators in Python: and, or, and not


In addition to boolean comparators, Python provides special keywords known as logical operators. These
operators are used to combine boolean expressions and construct compound logical expressions. There are
three logical operators in Python: and , or , and not . Let's delve into each of these operators:

1. The and Keyword:


The and keyword combines two boolean expressions and evaluates to True only if both expressions are True.
Here's a summary of how the and operator works:

Expression Result
True and True True
True and False False
False and True False

Page 4 of 21
Control_structures
Expression Result
False and False False

Examples:

print(1 < 2 and 3 < 4) # Output: True


print(2 < 1 and 4 < 3) # Output: False
print(1 < 2 and 4 < 3) # Output: False
print(2 < 1 and 3 < 4) # Output: False

2. The or Keyword:
The or keyword combines two boolean expressions and evaluates to True if at least one of the expressions is
True. Here's how the or operator behaves:

Expression Result
True or True True
True or False True
False or True True
False or False False

Examples:

print(1 < 2 or 3 < 4) # Output: True


print(2 < 1 or 4 < 3) # Output: False
print(1 < 2 or 4 < 3) # Output: True
print(2 < 1 or 3 < 4) # Output: True

3. The not Keyword:


The not keyword reverses the truth value of a single expression. Here's a summary:

Expression Result
not True False
not False True

Examples:

print(not True) # Output: False


print(not False) # Output: True

The not keyword is useful for negating the result of a boolean expression.

Writing Complex Expressions in Python


Page 5 of 21
Control_structures
In Python, you can create complex logical expressions by combining logical operators ( and , or , not ) with
boolean values ( True and False ). Let's understand how to write and evaluate such expressions with more
examples:

Example 1: Evaluating a Complex Expression


Consider the expression: True and not (1 != 1)
Step-by-Step Evaluation:
1. Evaluate the expression inside the parentheses: 1 != 1 . Since 1 is equal to itself, the expression
evaluates to False .
2. Apply the not operator to the result: not (False) , which evaluates to True .
3. Finally, evaluate True and True , which results in True .
Code Example:

result = True and not (1 != 1)


print(result) # Output: True

Example 2: Evaluating Another Complex Expression


Let's evaluate: ("A" != "A") or not (2 >= 3)
Step-by-Step Evaluation:
1. Evaluate the first expression in parentheses: "A" != "A" . Since "A" is equal to itself, the expression
evaluates to False .
2. Evaluate the second expression in parentheses: 2 >= 3 . Since 2 is not greater than or equal to 3 ,
the expression evaluates to False .
3. Apply the not operator to the result of the second expression: not (False) , which results in True .
4. Finally, evaluate False or True , which results in True .
Code Example:

result = ("A" != "A") or not (2 >= 3)


print(result) # Output: True

Example 3: Using Parentheses for Clarity


Parentheses can be used to group expressions and clarify the order of operations.
Code Example:

result = (True and False) == (True and False)


print(result) # Output: True

More Examples:
Page 6 of 21
Control_structures
Example 4: Complex Expression with Mixed Operators
result = (3 < 5) and (10 >= 8) or not (5 == 5)
print(result) # Output: True

Example 5: Using Parentheses for Order of Evaluation


result = 3 < 5 and (10 >= 8 or not 5 == 5)
print(result) # Output: False

Example 6: Complex Expression with Multiple Operators


result = (True and False) or (not True and True) and (False or True)
print(result) # Output: False

Class Excercise
1. Figure out what the result will be (True or False) when evaluating
the following expressions, then type them into the interactive window to check your answers:
a. (1 <= 1) and (1 != 1)
b. not (1 != 2)
c. ("good" != "bad") or False
d. ("good" != "Good") and not (1 == 1)

2. Add parentheses where necessary so that each of the following expressions evaluates to
True:
1. False == not True
2. True and False == True and False
3. not True and "A" == "B"

Understanding the if Statement


Concept:
The if statement is a powerful tool in programming that allows us to make decisions based on certain
conditions. It helps create what's called a decision structure, enabling our program to choose different paths of
execution depending on whether a condition is true or false.

Control Structures:
In programming, a control structure is a logical design that manages the order in which statements execute. So
far, we've mainly used the sequence structure, where statements execute in the order they appear. However,
sometimes problems require more complex solutions than just executing statements one after another.

Decision Structures:
Page 7 of 21
Control_structures
When we need our program to make decisions based on conditions, we use decision structures. These
structures, also known as selection structures, allow us to execute a set of statements only under specific
circumstances.
Beyond Simple Sequences
So far, you might have encountered programs that just execute instructions one after another, like this:

name = input("What is your name? ")


age = int(input("What is your age? "))
print("Here is the data you entered:")
print("Name:", name)
print("Age:", age)

The Basic Decision: At its core, a decision structure involves performing an action only if a certain condition
exists. If the condition is true, the action is performed; if not, it's skipped. Think of it like making everyday
decisions - if it's cold outside, you wear a coat; if it's not, you don't.
Single Alternative Decision Structure: A basic decision structure with only one alternative path of execution
is called a single alternative decision structure. If the condition is true, we follow the alternative path; otherwise,
we exit the structure.

Example: Imagine a scenario where we want to print a message only if it's raining:

if raining:
print("Bring an umbrella!")

Syntax of the if Statement: In Python, the if statement is used to create single alternative decision
structures. Here's its general format:

if condition:
statement
statement
# more statements if needed

The condition is evaluated, and if it's true, the statements inside the if block are executed. If the condition is
false, those statements are skipped, and the program continues execution.

Page 8 of 21
Control_structures

Making Decisions in Python: The Power of if Statements


Imagine you're writing a program that needs to react differently based on certain situations. That's where if
statements come in! They act as decision-makers, controlling the flow of your code and executing specific blocks
only when a condition is met.
Understanding Control Flow
Think of programs as having different paths they can take. A simple program might just execute instructions
from top to bottom, but if statements allow for more complex decision-making.
This is a sequence structure, where instructions are followed in order. However, some problems require more.
Making Choices: Enter the if Statement
if statements introduce decision structures, allowing your program to choose between different paths based
on certain conditions. Imagine a program that calculates overtime pay:
If an employee works more than 40 hours, they get paid extra for those extra hours.
Otherwise, the overtime calculation is skipped.
This requires a decision structure, where the program checks a condition (working hours) and executes different
code blocks accordingly.
Translating Flowchar ts to Code: The if Statement in Action
In Python, the if statement lets you write single-alternative decision structures. Here's the basic format:

if condition:
# Code to execute if the condition is True

Breakdown:
1. if keyword: This initiates the decision-making process.
2. condition : This is a Boolean expression that evaluates to either True or False . Think of it as the
question the program needs to answer.
3. Colon ( : ): This marks the end of the condition and the beginning of the indented code block.
4. Indented code block: This block contains the code that executes only if the condition is True .
Proper indentation is crucial here (usually using spaces or tabs).
Making the Choice: The Condition's Role
The condition is the heart of the decision. It's a Boolean expression that determines whether the indented
code block runs. If the condition evaluates to True , the code within the block executes. If it's False , the code
is skipped, and the program continues to the next line.
Example: Checking Age Eligibility

age = 18
if age >= 18: # Checking if age is greater than or equal to 18
print("You are eligible to vote.")

Page 9 of 21
Control_structures
In this example, the code checks if age is 18 or older. If it is ( True ), the message "You are eligible to vote" is
printed. If not ( False ), the program simply skips the indented block and continues execution.
The if Statement: A Gatekeeper for Code
Think of an if statement as a gatekeeper who controls access to a specific area. The gatekeeper only allows
entry if a certain requirement is fulfilled.
Example:

x = 10
if x > 5:
print("x is greater than 5")

Explanation:
The if keyword signals the start of the conditional statement.
After the if keyword, there's a test condition followed by a colon ( : ).
If the condition is True , the indented block of code under the if statement is executed.
If the condition is False , the indented block of code is skipped.
More Examples and Explanations:
1. Checking for Even Numbers:

num = 6
if num % 2 == 0:
print("The number is even")

Explanation: This if statement checks if the number num is divisible by 2 with no remainder, indicating that it's
even.
2. Checking for Positive Numbers:

value = -5
if value > 0:
print("The number is positive")

Explanation: Here, the if statement verifies if the value is greater than 0, indicating that it's positive.
3. Checking for a Specific String:

name = "Vini"
if name == "Vini":
print("Welcome, Alice!")

Explanation: This if statement compares the value of the variable name to the string "Vini" and prints a
welcome message if they match.
4. Verifying User Input:

Page 10 of 21
Control_structures

user_input = input("Enter 'yes' or 'no': ")


if user_input.lower() == 'yes':
print("You entered 'yes'.")

Explanation: This example prompts the user to input either 'yes' or 'no'. The if statement checks if the input is
'yes' (case-insensitive) and provides feedback accordingly.
5. Checking for a Range of Values:

age = 25
if 18 <= age <= 30:
print("You are in the young adult age range.")

Explanation: This if statement verifies if the age falls within the range of 18 to 30, inclusively.
Remember :
if statements control the flow of your code based on conditions.
The condition must be a Boolean expression (evaluates to True or False ).
Code within an if block only executes if the condition is True .
Proper indentation is essential for Python to recognize the code block within the if statement.

Problem Using the if Statement


Kathryn teaches a science class and her students are required to take three tests. She wants to write a program
that her students can use to calculate their average test score. She also wants the program to congratulate the
student enthusiastically if the average is greater than 95. Here is the algorithm in pseudocode:
Get the first test score
Get the second test score
Get the third test score
Calculate the average
Display the average
If the average is greater than 95: - Congratulate the user

Page 11 of 21
Control_structures

# Get the first test score from the user


test_1 = float(input("Enter your first test score: "))
# Get the second test score from the user
test_2 = float(input("Enter your second test score: "))
# Get the third test score from the user
test_3 = float(input("Enter your third test score: "))
# Calculate the average score
average_score = (test_1 + test_2 + test_3) / 3
# Display the average score
print("Your average test score is:", average_score)
# Check if the average is greater than 95 using an if statement
if average_score > 95:
# Congratulate the user enthusiastically if the condition is True
print("Congratulations! That's an excellent score! ")

Explanation:
1. Input: The program uses input() to get the test scores from the user. The float() function
converts the input (which is initially text) to floating-point numbers for calculations.
2. Calculation: The average score is calculated by adding the three test scores and dividing by 3.
3. Display Average: The calculated average is displayed using print() .
4. Decision Making ( if statement):
The if statement checks if the average_score is greater than 95.
If the condition ( average_score > 95 ) is True , the indented code block executes, printing
a congratulatory message.
If the condition is False (average is not greater than 95), the program continues to the next
line (no congratulation message is printed).

Understanding the if-else Statement


Concept: The if-else statement is a fundamental tool in programming that allows us to execute one block of
code if a condition is true, and another block if the condition is false. It's like making a decision: if something is
true, we do one thing; if it's not true, we do something else.
Dual Alternative Decision Structure: Imagine having two possible paths to take based on a condition - one
path if it's true, and another if it's false. That's the essence of a dual alternative decision structure. It's like
deciding what to wear: if it's cold, we wear a coat; if it's not, we wear something lighter.

Page 12 of 21
Control_structures

Syntax of the if-else Statement: In Python, we use the if-else statement to create dual alternative
decision structures. Here's how it looks:

if condition:
# statements to execute if condition is true
# ...
else:
# statements to execute if condition is false
# ...

If the condition is true, the statements


inside the if block are executed; otherwise, the statements inside the else block are executed.
Example: Let's say we want to print a message based on the temperature:

if temperature < 40:


print("A little cold, isn't it?")
else:
print("Nice weather we're having.")

If the temperature is less than 40, we print "A little cold, isn't it?"; otherwise, we print "Nice weather we're
having."
Indentation: In Python, indentation is crucial. When writing an if-else statement:
Ensure that the if and else clauses are aligned.
The blocks of statements inside the if and else clauses should be consistently indented.

Page 13 of 21
Control_structures
Problem to Solve
Chris owns an auto repair business and has several employees. If any employee works over 40 hours in a week,
he pays them 1.5 times their regular hourly pay rate for all hours over 40. He has asked you to design a simple
payroll program that calculates an employee’s gross pay, including any overtime wages.

Formula for Calculating Payroll:


Gross Pay = Regular Pay + Overtime Pay
Regular Pay = Hours Worked * Hourly Pay Rate
Overtime Pay = Overtime Hours * Overtime Pay Rate
Overtime Hours = Hours Worked - 40 (if Hours Worked > 40)
Overtime Pay Rate = 1.5 * Hourly Pay Rate

Payroll Calculation Program using the if-else Statement

# Get input from user


hours_worked = float(input("Enter the number of hours worked: "))
hourly_pay_rate = float(input("Enter the hourly pay rate: "))
# Calculate gross pay
if hours_worked > 40:
overtime_hours = hours_worked - 40
overtime_pay_rate = 1.5 * hourly_pay_rate
gross_pay = (40 * hourly_pay_rate) + (overtime_hours * overtime_pay_rate)
print("Gross pay with overtime: Le", gross_pay)
else:
gross_pay = hours_worked * hourly_pay_rate
print("Gross pay: Le", gross_pay)

Explanation:
We first get the number of hours worked and the hourly pay rate from the user.
Then, we check if the number of hours worked is greater than 40. If it is, we calculate the overtime pay.
Overtime pay is calculated by multiplying the overtime hours by 1.5 times the regular hourly pay rate.
Gross pay is then calculated by adding regular pay (for the first 40 hours) and overtime pay.
If the number of hours worked is 40 or less, we simply calculate the gross pay using the regular pay rate.
Additional Problems for Class Exercise:
1. Sales Commission Calculation:
Design a program that calculates a salesperson's commission based on their total sales.
If total sales are over Le10,000, the commission rate is 5%. Otherwise, it's 2.5%.
Calculate and display the commission earned by the salesperson.

Nested if Statements
Definition: Nested if statements are if statements within other if statements. They allow for multiple levels of
decision-making within a program. In other words, you can have conditions within conditions.
Syntax:
Page 14 of 21
Control_structures

if condition1:
# Block of code
if condition2:
# Nested block of code
else:
# Another nested block of code
else:
# Another block of code

Explanation:
The outer if statement is evaluated first.
If its condition is true, the inner if statement (nested within the outer if) is evaluated.
If the condition of the inner if statement is true, its block of code executes.
If the condition of the inner if statement is false, its else block (if provided) executes.
If the condition of the outer if statement is false, its else block (if provided) executes.
Example: Let's say we want to determine the grade of a student based on their score and attendance:

score = 85
attendance = True
if score >= 80:
if attendance:
print("Grade: A")
else:
print("Grade: B")
else:
print("Grade: C")

In this example:
If the score is 80 or above, we check attendance.
If attendance is true, the student gets an 'A' grade.
If attendance is false, the student gets a 'B' grade.
If the score is below 80, the student gets a 'C' grade.
More Problems for Practice:
1. Nested if for Voting Eligibility:
Create a program that asks the user for their age.
If the age is 18 or above, ask if they are registered to vote.
If they are registered, print "You are eligible to vote."
If they are not registered, print "Please register to vote."
If the age is below 18, print "You are not eligible to vote."
2. Nested if for Deliver y Charges:
Design a program that calculates delivery charges based on the weight of a package and the
Page 15 of 21
Control_structures
distance it needs to travel.
If the weight is over 10 kg, check if the distance is over 100 km.
If it is, the delivery charges are Le10 per kg.
If not, the delivery charges are Le5 per kg.
If the weight is 10 kg or less, check if the distance is over 50 km.
If it is, the delivery charges are Le7 per kg.
If not, the delivery charges are Le3 per kg.
1. Nested if for Voting Eligibility:

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


if age >= 18:
registered = input("Are you registered to vote? (yes/no): ")
if registered.lower() == "yes":
print("You are eligible to vote.")
else:
print("Please register to vote.")
else:
print("You are not eligible to vote.")

Explanation:
We first get the user's age as input.
If the age is 18 or above, we ask if they are registered to vote.
If they are registered, we print "You are eligible to vote."
If they are not registered, we print "Please register to vote."
If the age is below 18, we print "You are not eligible to vote."
2. Nested if for Deliver y Charges:

weight = float(input("Enter the weight of the package (in kg): "))


distance = float(input("Enter the distance to travel (in km): "))
if weight > 10:
if distance > 100:
delivery_charges = 10 * weight
else:
delivery_charges = 5 * weight
elif weight <= 10:
if distance > 50:
delivery_charges = 7 * weight
else:
delivery_charges = 3 * weight
print(f"Delivery charges: Le{delivery_charges}")

Explanation:
We get the weight of the package and the distance to travel as input.
If the weight is over 10 kg, we check the distance:
Page 16 of 21
Control_structures
If it's over 100 km, the delivery charges are Le10 per kg.
If it's not, the delivery charges are Le5 per kg.
If the weight is 10 kg or less, we check the distance:
If it's over 50 km, the delivery charges are Le7 per kg.
If it's not, the delivery charges are Le3 per kg.
elif Statements
Definition: elif statements, short for "else if," are used to add additional conditions to an if statement. They
provide an alternative option when the initial condition of the if statement is false.
Syntax:

if condition1:
# Block of code
elif condition2:
# Another block of code
elif condition3:
# Yet another block of code
else:
# Default block of code

Explanation:
The if statement is evaluated first.
If its condition is true, the corresponding block of code executes, and the program skips the rest of the
elif and else clauses.
If the condition of the if statement is false, the program moves on to the first elif statement and
evaluates its condition.
If the condition of the elif statement is true, its block of code executes, and the program skips the
remaining elif and else clauses.
This process continues until a condition is true or until the else clause is reached, in which case the block
of code associated with the else clause executes.
Example: Let's say we want to assign a letter grade to a student based on their score:

score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")

In this example:

Page 17 of 21
Control_structures
If the score is 90 or above, the student gets an 'A' grade.
If the score is between 80 and 89, the student gets a 'B' grade.
If the score is between 70 and 79, the student gets a 'C' grade.
If the score is between 60 and 69, the student gets a 'D' grade.
If the score is below 60, the student gets an 'F' grade.
More Problems for Practice:
1. Eligibility for Discounts:
Create a program that determines whether a customer is eligible for a discount based on their
total purchase amount.
If the purchase amount is Le100 or more, the customer gets a 10% discount.
If the purchase amount is between Le50 and Le99.99, the customer gets a 5% discount.
If the purchase amount is less than Le50, the customer does not get a discount.
2. Health Risk Assessment:
Design a program that assesses a person's health risk based on their body mass index (BMI).
If the BMI is 30 or above, the person is classified as obese.
If the BMI is between 25 and 29.9, the person is classified as overweight.
If the BMI is between 18.5 and 24.9, the person is classified as normal weight.
If the BMI is below 18.5, the person is classified as underweight.
Problem 1: Eligibility for Discounts

purchase_amount = float(input("Enter the total purchase amount: Le"))


if purchase_amount >= 100:
discount = purchase_amount * 0.1
discounted_amount = purchase_amount - discount
print(f"You are eligible for a 10% discount. Your discounted amount is:
Le{discounted_amount:.2f}")
elif 50 <= purchase_amount < 100:
discount = purchase_amount * 0.05
discounted_amount = purchase_amount - discount
print(f"You are eligible for a 5% discount. Your discounted amount is:
Le{discounted_amount:.2f}")
else:
print("Sorry, you are not eligible for any discount.")

Problem 2: Health Risk Assessment

Page 18 of 21
Control_structures

height = float(input("Enter your height (in meters): "))


weight = float(input("Enter your weight (in kilograms): "))
bmi = weight / (height ** 2)
if bmi >= 30:
print(f"Your BMI is {bmi:.2f}, indicating that you are obese.")
elif 25 <= bmi < 30:
print(f"Your BMI is {bmi:.2f}, indicating that you are overweight.")
elif 18.5 <= bmi < 25:
print(f"Your BMI is {:.2f}, indicating that you are of normal weight.")
else:
print(f"Your BMI is {bmi:.2f}, indicating that you are underweight.")

Explanation:
For the first problem, we check the purchase amount using if and elif statements to determine the
discount percentage and calculate the discounted amount accordingly.
For the second problem, we calculate the BMI using the provided height and weight inputs and then use
if and elif statements to classify the BMI into different health risk categories.

Problems to Solve
1. Mass and Weight
Scientists measure an object’s mass in kilograms and its weight in newtons. If you know
the amount of mass of an object in kilograms, you can calculate its weight in newtons with
the following formula:
weight = mass * 9.8
Write a program that asks the user to enter an object’s mass, then calculates its weight. If
the object weighs more than 500 newtons, display a message indicating that it is too heavy.
If the object weighs less than 100 newtons, display a message indicating that it is too
light.
2. Grade Calculator
A class has two tests worth 25 points each along with a main exam worth 50 points. For a
student to pass the class, they must obtain at least 25 points in the main exam and an
overall
score of at least 50 points. If a student’s total score is less than 50 or they obtain less
than 25
points in the main exam, they receive a grade of “Fail”. Otherwise, their grade is as
follows:
• If they get more than 80, they get a “Distinction” grade.
• If they get less than 80 but more than 60, they get a “Credit” grade.
• If they get less than 60, they get a “Pass” grade.
Write a program that prompts the user to enter their points for both tests and the main
exam and converts the values to integers. The program should first check if the points
entered for the tests and main exam are valid. If any of the test scores are not between 0
and
25 or the main exam score is not between 0 and 50, the program should display an error
message. Otherwise, the program should display the total points and the grade.
3. Loan Approval
Design a program that assesses whether a user is eligible for a loan based on their credit
Page 19 of 21
Control_structures
Design a program that assesses whether a user is eligible for a loan based on their credit
score and income level. Prompt the user to enter their credit score (on a scale of 300 to
850) and their annual income. Determine loan eligibility using the following criteria:
Credit score >= 700 and income >= Le50,000: Eligible for loan approval
Credit score >= 650 and income >= Le40,000: Conditional approval pending further
verification
Otherwise: Not eligible for loan approval
Output a message indicating the user's loan eligibility status.
4.Ticket Pricing
Develop a program that calculates ticket prices for a movie theater based on the age of the
customer and whether they are a student or a senior citizen. Prompt the user to enter their
age and indicate whether they are a student or a senior. Then, determine the ticket price
according to the following rules:
Children (age 0-12): Le5
Teenagers (age 13-18): Le8
Adults (age 19-64): Le10
Seniors (age 65 and above): Le6
Students (regardless of age): Le7 (applicable if the user is a student)
5. Body Mass Index (BMI) Calculator
Design a program that calculates a person's body mass index (BMI) based on their height and
weight inputs. The program should prompt the user to enter their height in meters and weight
in kilograms. Then, it should calculate the BMI using the formula BMI = weight / (height^2)
and categorize the BMI into underweight, normal weight, overweight, or obese based on the
following criteria:
Underweight: BMI < 18.5
Normal weight: 18.5 <= BMI < 25
Overweight: 25 <= BMI < 30
Obese: BMI >= 30
Provide appropriate feedback to the user based on their BMI category.
6. Leap Year Checker
Write a program that prompts the user to enter a year and then determines whether the year
entered is a leap year or not. A year is a leap year if it is divisible by 4 but not
divisible by 100 unless it is also divisible by 400. Output a message indicating whether the
year is a leap year or not.

Page 20 of 21
Control_structures

created with the evaluation version of Markdown Monster

Page 21 of 21

You might also like