Week 4 – Control
Structures: Selection
Learning Objectives:
• Write Python programs that use if, elif, and else statements to make
choices based on conditions.
• Utilize for and while loops to execute a block of code multiple times.
• Design nested loops and leverage loop control statements (break,
continue) to solve complex problems.
• Debug and optimize Python code using control structures and loop
control statements.
Review of Indention
• Indentation is used in Python to delimit blocks.
• The number of spaces is variable, but all statements
within the same block must be indented the same
amount.
• The header line for compound statements, such as if,
while, def, and class should be terminated with a
colon (: )
• The semicolon ( ; ) is optional at the end of
statement.
Control Structures
• Statements in a program are executed sequentially,
from the first statement to the last statement.
• Control structures provide a means for some
statements to be skipped or by-passed during
execution, depending on the result of a condition(s).
Review of Control Structure
(Flowcharting)
A. Sequence
B. Selection (or Conditional) Structure
C. Iteration (or Repetition/Looping) Structure
A B C
Selection/ Conditional Structure
• Provides a choice between two or more alternatives
• 3 components of the structure:
• A condition to be tested
• The statement to be performed if the condition is
satisfied (process A)
• The statement to be performed if the condition is not
satisfied (process B)
• Entry to the structure is through the condition
• Exit is through the execution of process A or process
B
Selection/Conditional Statements
• The if statement
• The if-else statement
• The if-elif-else statements
• The nested-if statement
If Statement
• The if statement is the most simple decision-making
statement. It is used to decide whether a certain
statement or block of statements will be executed or not.
#if syntax if condition:
statement1
if condition:
Statement2
statement1
or
if condition: # Here if the condition is true,
# if block will consider only #shorthand if statement
statement1
statement2 # statement1 to be inside its
# Statements to execute if condition is true # block. if condition: statement
Shorthand: the statement can be put on the
condition is a boolean expression or boolean variable same line as the if statement.
Review Boolean Expression and
Operators
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
Example
# python program to illustrate If statement
i = 10 gpa = 3.4
if i > 15: if gpa > 2.0:
print("10 is less than 15") print "Your application is accepted."
print("I am Not in if")
Example
If Else Statement
• The if/else statement executes one block of
statements if a certain condition is True, and a
second block of statements if it is False.
if condition:
statement
# Executes this block if
# condition is true
else:
statement
# Executes this block if
# condition is false
Example
# python program to illustrate else if in Python statement
i = 20
if i < 15:
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Example # Shorthand if/else syntax
statement_when_True if condition else statement_when_False
a = b = 4.5 #Another conditional structure
if a>b: # in Python
x = 'smaller'
else: a = b = 4.5
x = 'bigger' x = 'smaller' if a < b else 'bigger'
print(x)
gpa = 1.4
Example
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
OR
gpa = 1.4
print("Welcome to Mars University") if gpa > 2.0 else print("Your application is denied")
Example
Example
raining = False
print("Let's go to the", 'beach' if not raining else 'library’)
# Display Let's go to the beach
raining = True
print("Let's go to the", 'beach' if not raining else 'library’)
# Display Let's go to the library
age = 12
s = 'minor' if age < 21 else 'adult’
print(s)
# Display minor
Guess the value of x
x = 20
y = 40
#A
z = 1 + x if x > y else y + 2
print(z)
#B
z = (1 + x) if x > y else (y + 2)
print(z)
z = 1 + (x if x > y else y) + 2
print(z)
If/Elif/Else Statement
• Here, a user can decide among
multiple options. The if if (condition):
statements are executed from the statement
top down. elif (condition):
statement
• As soon as one of the conditions
elif (condition):
controlling the if is true, the statement
statement associated with that if .
is executed, and the rest of the .
ladder is bypassed. If none of the else:
conditions is true, then the final statement
“else” statement will be
executed.
• elif – short for “else if”
Example
# Python program to illustrate if-elif-else ladder
i = 20 a = 200
if (i == 10): b = 33
print("i is 10") if b > a:
elif (i == 15): print("b is greater than a")
print("i is 15") elif a == b:
elif (i == 20): print("a and b are equal")
print("i is 20") else:
else: print("a is greater than b")
print("i is not present")
Example
letter = "A"
grade = int(input("Enter your grade (0-100): "))
if letter == "B":
print("letter is B")
if grade >= 90:
print("Excellent! You earned an A.")
elif letter == "C":
elif grade >= 80:
print("letter is C")
print("Very good! You earned a B.")
elif grade >= 70:
elif letter == "A":
print("Good job! You earned a C.")
print("letter is A")
else:
print("You may need to study more. You earned a D or F.")
else:
print("letter isn't A, B or C")
day_number = int(input("Enter a number between 1 and 7 (corresponding to days of the week): "))
if day_number == 1:
print("It's Monday!")
elif day_number == 2:
print("It's Tuesday!")
elif day_number == 3:
print("It's Wednesday!")
elif day_number == 4:
print("It's Thursday!")
elif day_number == 5:
print("It's Friday!")
elif day_number == 6:
print("It's Saturday!")
elif day_number == 7:
print("It's Sunday!")
else:
print("Invalid input. Please enter a number between 1 and 7.")
Example
Example
# python program to illustrate nested If statement age = int(input("Enter your age: "))
i = 10 has_license = input("Do you have a driver's license (yes/no)?
if (i == 10): ").lower()
# First if statement if age >= 16:
if (i < 15): if has_license == "yes":
print("i is smaller than 15") print("You are eligible to drive.")
else:
# Nested - if statement print("You are eligible to apply for a learner's permit, but cannot
# Will only be executed if statement above drive yet.")
# it is true else:
if (i < 12): print("You are not old enough to drive.")
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Example
# if..else chain statement
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")
Example
age = int(input("Enter your age: "))
has_license = input("Do you have a driver's license (yes/no)? ").lower()
if age >= 16:
if has_license == "yes":
print("You are eligible to drive.")
else:
print("You are eligible to apply for a learner's permit, but cannot drive yet.")
else:
print("You are not old enough to drive.")
Compound Conditions
• Have more than 1 conditional expression
• The result of the compound expression depends on the individual
result of each condition
if (condition1) and (condition2):
statement
if (condition1) or (condition2):
statement
and, or, not
In Python, and, or, and not are logical operators used to combine conditional
statements and evaluate truth values.
• and (Logical AND):
• Returns True only if both operands (conditions) being evaluated are True.
• If even one operand is False, the entire expression becomes False.
age = 20
has_license = True
if age >= 16 and has_license:
print("You are eligible to drive.")
else:
print("You are not eligible to drive.")
and, or, not
is_weekday = True
is_working_hours = True
# Check if it's a weekday AND working hours (both conditions must be true)
is_work_time = is_weekday and is_working_hours
if is_work_time:
print("Time to get to work!")
else:
print("Enjoy your free time!")
and, or, not
• or (Logical OR):
• Returns True if at least one operand being evaluated is True.
• It returns False only if all operands are False.
is_rainy = True
is_weekend = False
# Check if it's raining or weekend (at least one condition must be true)
go_outside = is_rainy or is_weekend
if go_outside:
print("It's a good day to go outside!")
else:
print("Maybe stay indoors today.")
and, or, not
age = 12
has_permission = False
# Check if user is old enough (over 18) or has permission to access the game
can_play_game = age >= 18 or has_permission
if can_play_game:
print("Welcome! You can play the game.")
else:
print("Sorry, you cannot play this game yet.")
and, or, not
• not (Logical NOT):
• Inverts the truth value of the operand it acts on.
• If the operand is True, not makes it False.
• If the operand is False, not makes it True.
is_raining = False
if not is_raining:
print("It's a good day for a walk.")
else:
print("Stay indoors, it's raining!")
Example
grade = float(input("Enter your grade (0.0 to 100.0): "))
attendance_rate = float(input("Enter your attendance rate (0.0 to 1.0): "))
# Minimum requirements
min_grade = 90.0
min_attendance = 0.8
if grade >= min_grade and attendance_rate >= min_attendance:
print("Congratulations! You are eligible for the award.")
else:
if grade < min_grade:
print("Your grade is below the minimum requirement.")
if attendance_rate < min_attendance:
print("Your attendance rate is below the minimum requirement.")
print("You are not eligible for the award this time. Please try again next semester!")
Example
age = int(input("Enter your age: "))
is_member = input("Are you a library member (yes/no)? ").lower()
# Minimum age requirement
min_age = 13
if (age >= min_age and is_member == "yes") or (age < min_age and is_member == "yes" and has_parental_consent):
print("You are eligible to borrow books.")
else:
print("You are not eligible to borrow books yet.")
# Prompt for parental consent if needed
has_parental_consent = False
if age < min_age and is_member == "yes" and not has_parental_consent:
print("You need parental consent to borrow books as a minor.")
Example
desired_temp = float(input("Enter desired temperature: "))
current_temp = float(input("Enter current temperature: "))
ac_on = False
heater_on = False
# Temperature difference threshold
threshold = 2.0
if (current_temp > desired_temp + threshold) and not ac_on:
print("Turn on the AC. It's too hot!")
elif (current_temp < desired_temp - threshold) and not heater_on:
print("Turn on the heater. It's too cold!")
else:
print("The temperature is comfortable. No action needed.")
Example
isupper()
• Returns True if all characters in the string are upper case Format:
string.isupper()
islower()
• Returns True if all characters in the string are lower case Format:
string.islower()
isdigit()
• Returns True if all characters in the string are digits, otherwise False.
Subscripts and superscripts are also considered to be a digit. Format:
string.isdigit()
isalpha()
• Returns True if all characters in the string are in the alphabet Format:
string.isalpha()
Problem Set
• Write a simple python program that accepts Name, and grades for
Math, Science and English, respectively.
• Compute and display the average of the three subjects.
• If the rounded average is equal or greater than 75, the status is
Passed else You Failed the semester
Problem Set
Problem Set
Problem Set
Problem Set
• Write a simple python
program using the
selection structure that
will accept the Age and
Sex of the user, and display
his/her Room Assignment
based on the table at the
right.
Problem Set
• Develop an application that computes the areas of various shapes,
such as rectangles, circles, and triangles. To begin, consider the user's
interaction method for selecting the shape - possibly through numeric
codes (1 for rectangle) or alphabetical characters (R for rectangle).
Next, employ if-statements to handle each shape selection. Within
these if-conditions, ask the user for the specific dimensions required
(length/width, radius, base/height). Remember, each shape has its
unique area formula. Lastly, utilize these measurements along with
the respective formula to determine the area and present it to the
user.
THANK YOU
46