Lecture - 2 2
Lecture - 2 2
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
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
num = 6
print(num % 2 == 0) # Output: True
value = 25
print(10 <= value <= 30) # Output: True
num = 7
print(num % 2 != 0) # Output: True
num = 10
print(num > 0) # Output: True
Page 3 of 21
Control_structures
num = -5
print(num < 0) # Output: True
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"
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:
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:
Expression Result
not True False
not False True
Examples:
The not keyword is useful for negating the result of a boolean expression.
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
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"
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:
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
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
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.
Page 11 of 21
Control_structures
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).
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 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.
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:
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:
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
Page 18 of 21
Control_structures
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
Page 21 of 21