Module 3. Control Structures
Module 3. Control Structures
Example: is_admin = (user == "admin"). user is compared with "admin“ using the == operator, which tests for equality.
The Boolean variable, is_admin, is assigned with the Boolean result.
The if statement's body must be grouped together and have one level of indentation. The Python interpreter will produce an
error if the body is empty.
1. Given the following, which part is the condition? 2. Given num = -10, what is the final value of num?
An else statement is used with an if statement and contains a body of statements that is executed when the if statement's
condition is false. When an if-else statement is executed, one and only one of the branches is taken. That is, the body of the if
or the body of the else is executed.
Note: The else statement is at the same level of indentation as the if statement, and the body is indented.
a. x >= 15
b. x <= 15 a. 30 a. 30
c. x < 15 b. 40 b. 55
c. 50 c. 105
Exercise 3.2: Converting temperature units
The following program reads in a temperature as a float and the unit as a string: "f" for Fahrenheit or "c"
for Celsius.
Calculate new_temp, the result of converting temp from Fahrenheit to Celsius or Celsius to Fahrenheit
based on unit. Calculate new_unit: "c" if unit is "f" and "f" if unit is "c".
Conversion formulas:
• Degrees Celsius = (degrees Fahrenheit - 32) * 5/9
• Degrees Fahrenheit = (degrees Celsius * 5/9) + 32
# Sample output
Enter temperature: 70
Enter 'c' for Celcius and 'f' for Fahrenheit: f
70.0 degrees farenheit is equivalent to 21.11111111111111 degrees celcius.
Logical operator: and
Decisions are often based on multiple conditions.
Example: A program printing if a business is open may check that hour >= 9 and hour < 17. A logical operator takes condition
operand(s) and produces True or False.
Python has three logical operators: and, or, and not. The and operator takes two condition operands and
returns True if both conditions are true.
p q p and q
True True True
True False False
False True False
False False False
1. Given is_admin = False and is_online = True, what is the 2. Given x = 8 and y = 21, what is the final value of z?
value of is_admin and is_online?
if (x < 10) and (y > 20):
a. True z=5
b. False else:
z=0
a. 0
b. 5
Logical operator: or
Sometimes a decision only requires one condition to be true.
Example: If a student is in the band or choir, they will perform in the spring concert. The or operator takes two condition
operands and returns True if either condition is true.
p q p and q
True True True
True False False
False True False
False False False
1. Given days = 21 and is_damaged is False, is the refund 2. For what values of age is there no discount?
processed?
if (age < 12) or (age > 65):
if (days < 30) or is_damaged: # Apply student/senior discount
# Process refund
a. age >= 12
a. yes b. age <= 65
b. no c. (age >= 12) and (age <= 65)
Logical operator: not
If the computer is not on, press the power button. The not operator takes one condition operand and returns
True when the operand is false and returns False when the operand is true.
not is a useful operator that can make a condition more readable and can be used to toggle a Boolean's value.
True False
False True
1. Given x = 13, what is the value of not(x < 10)? 2. Given x = 18, is x in the correct range?
a. True
b. False
Exercise 3.3: Speed limits
Write a program that reads in a car's speed as an integer and checks if the car's speed is within the freeway
limits. A car's speed must be at least 45 mph but no greater than 70 mph on the freeway.
If the speed is within the limits, print "Good driving". Else, print "Follow the speed limits".
# Sample output
Enter car's speed: 75
Follow the speed limits.
When an expression has multiple operators, which operator is evaluated first? Precedence rules provide the priority level of
operators.
Example: 1 + 2 * 3 is 7 because multiplication takes precedence over addition. However, (1 + 2) * 3 is 9 because parentheses
take precedence over multiplication.
Operator Meaning
() Parenthesis
** Exponentiation (right associative)
*, /, //, % Multiplication, division, floor division, modulo
+, - Addition, subtraction
<, <=, >, >=, ==, != Comparison operators
Operator Meaning
not Logical not operator
and Logical and operator
or Logical or operator
Which part of the expression is evaluated first?
1. x ** 2 + 6 / 3 2. not 3 * 5 > 10
a. 6 / 3 a. 3 * 5
b. x ** 2 b. not 3
c. 2 + 6 c. 5 > 10
A conditional expression (also known as a "ternary operator") is a simplified, single-line version of an if-else statement.
A conditional expression is evaluated by first checking the condition. If condition is true, expression_if_true is evaluated, and
the result is the resulting value of the conditional expression. Else, expression_if_false is evaluated, and the result is the resulting
value of the conditional expression.
A variable can be assigned with a conditional expression. Ex: Finding the max of two numbers can be
calculated with max_num = y if x < y else x
Note: Conditional expressions have the lowest precedence of all Python operations.
1. What is the conditional expression version of the 2. Given x = 100 and offset = 10, what is the value of
following if-else statement? result?
Example: The software on a phone repeatedly checks to see if the phone is idle. Once the time set by a user is reached, the
phone is locked. Loops can also be used for iterating over lists like student names in a roster, and printing the names one at a
time.
In this chapter, two types of loops, for loop and while loop, are introduced. This chapter also introduces break and continue
statements for controlling a loop's execution.
A while loop is a code construct that runs a set of statements, known as the loop body, while a given condition, known as the
loop expression, is true. At each iteration, once the loop statement is executed, the loop expression is evaluated again.
• If true, the loop body will execute at least one more time (also called looping or iterating one more time).
• If false, the loop's execution will terminate and the next statement after the loop body will execute.
Example: A programmer may want to print all even numbers between 1 and 20. The task can be done by using a counter
initialized with 1. In each iteration, the counter's value is increased by one, and a condition can check whether the counter's
value is an even number or not. The change in the counter's value in each iteration is called the step size. The step size can be
any positive or negative value. If the step size is a positive number, the counter counts in ascending order, and if the step size is
a negative number, the counter counts in descending order.
Example 3.1
A program printing all odd numbers between 1 and 10.
Once the input “close" is received, print "The while loop condition has been met.“.
Enter different input words to see when the while loop condition is met.
# Sample output
Enter a word: hi
You entered: hi
Enter a word: everyone
You entered: everyone
Enter a word: good
You entered: good
Enter a word: afternoon
You entered: afternoon
Enter a word: close
End of while loop!
Exercise 3.6: Sum of odd numbers
Write a program that reads two integer values, n1 and n2. Use a while loop to calculate the sum of odd
numbers between n1 and n2 (inclusive of n1 and n2). Remember, a number is odd if number % 2 != 0.
# Sample output
Number 1: 1
Number 2: 5
The sum of numbers from 1 to 5 is: 9
In Python, a container can be a range of numbers, a string of characters, or a list of values. To access objects within a
container, an iterative loop can be designed to retrieve objects one at a time. A for loop iterates over all elements in a
container.
The range() function can take up to three input values. Examples are provided in the table below.
# Sample output
User input >>>Hi, everyone. Have a good day!
Number of spaces: 5
Exercise 3.8: Sequences
Write a program that reads two integer values, num1 and num2, with num1 < num2, and performs the following tasks:
1. Prints all even numbers between the two provided numbers (inclusive of both), in ascending order.
2. Prints all odd numbers between the two provided numbers (exclusive of both), in descending order.