0% found this document useful (0 votes)
6 views

Module 3. Control Structures

Uploaded by

Astrid Stavros
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)
6 views

Module 3. Control Structures

Uploaded by

Astrid Stavros
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/ 27

By the end of this section, you should be able to

• Explain a Boolean value.


• Use bool variables to store Boolean values.
• Demonstrate converting integers, floats, and strings to Booleans.
• Demonstrate converting Booleans to integers, floats, and strings.
• Use comparison operators to compare integers, floats, and strings.
• Explain the loop construct in Python.
• Use a while loop to implement repeating tasks.
Comparison operators are used to compare values, and the result is either true or false.

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 6 comparison operators:


• equal to: ==
• not equal to: !=
• greater than: >
• less than: <
• greater than or equal to: >=
• less than or equal to: <=

Let’s answer this one:


x = 14 w=0 v=4
compare_result = (x <= 13) compare_result = (w != 0.4) compare_result = (v < 4.0)

a. True a. True a. True


b. False b. False b. False
Exercise 3.1: Even numbers
Write a program that reads in an integer and prints whether the integer is even or not. Remember, a
number is even if the number is divisible by 2. To test this use number % 2 == 0.

Example: If the input is 10, the output is “10 is even: True".


If statement
A condition is an expression that evaluates to true or false. An if statement is a decision-making structure
that contains a condition and a body of statements. If the condition is true, the body is executed. If the
condition is false, the body is not executed.

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.

Using Boolean variables


A Boolean variable already has a value of True or False and can be used directly in a condition rather than
using the equality operator.

Example: if is_raining == True: can be simplified to if is_raining.

1. Given the following, which part is the condition? 2. Given num = -10, what is the final value of num?

if age < 12: if num < 0:


print("Discount for children available") num = 25
if num < 100:
a. age num = num + 50
b. age < 12
c. print("Discount for children available") a. -10
b. 40
c. 75
An if statement defines actions to be performed when a condition is true. What if an action needs to be performed only when
the condition is false? Ex: If the restaurant is less than a mile away, we'll walk. Else, we’ll drive.

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.

if-else statement template:


# Statement's before
if condition:
# Body
else:
# Body
1. Given the following code, the else 2. Given x = 40, what is the final 3. Given y = 50, which is not a
branch is taken for which range of x? value of y? possible final value of y?

if x >= 15: if x > 30: if x < 50:


# Do something y = x - 10 y=y/2
else: else: else:
# Do something else y = x + 10 y=y*2

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.

Example: is_on = not is_on.


p not p

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 if not(x > 15 and x < 20):


b. False # x in 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.

Operators with the highest precedence execute first.

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.

Conditional expression template:

expression_if_true if condition else expression_if_false

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?

if x % 2 == 0: result = x + offset if x < 100 else x - offset


response = 'even'
else: a. .90
response = 'odd’ b. 100
c. 110
a. response = if x%2 == 0 "even" else "odd“
b. response = "odd" if x%2 == 0 else "even"
c. response = "even" if x%2 == 0 else "odd"
Exercise 3.4: Ping values
Write a program that reads in an integer, ping, and prints ping_report, a string indicating whether the ping is low to average or
too high. ping values under 150 have a ping_report of "low to average". ping values of 150 and higher have a ping_report of
"too high". Use a conditional expression to assign ping_report.

Example: If the input is 30, the output is "Ping is low to average".


A loop is a code block that runs a set of statements while a given condition is true. A loop is often used for performing a
repeating task.

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.

Counting with a while loop


A while loop can be used to count up or down. A counter variable can be used in the loop expression to determine the
number of iterations executed.

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.

# A program printing all odd numbers between 1 and 10


# Initialization
counter = 1
# while loop condition
while counter <= 10:
if counter % 2 == 1:
print(counter)
# Counting up and increasing counter's value by 1 in each iteration
counter += 1
Exercise 3.5: Reading inputs in a while loop
Write a program that takes user inputs in a while loop until the user enters “close". Test the code with the given input values to
check that the loop does not terminate until the input is “close".

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.

Example: Iterating over a class roster and printing students' names.

Range() function in for loop


A for loop can be used for iteration and counting. The range() function is a common approach for implementing counting in a
for loop. A range() function generates a sequence of integers between the two numbers given a step size. This integer
sequence is inclusive of the start and exclusive of the end of the sequence.

The range() function can take up to three input values. Examples are provided in the table below.

Range function Description Example Output


range(end) • Generates a sequence beginning at 0 until end. range(4) 0, 1, 2, 3
• Step size: 1

range(start, end) • Generates a sequence beginning at start until end. range(0, 3) 0, 1, 2


• Step size: 1 range(2, 6) 2, 3, 4, 5
range(-13, -9) -13, -12, -11, -10
range(start, end, step) • Generates a sequence beginning at start until end. range(0, 4, 1) 0, 1, 2, 3
• Step size: step range(1, 7, 2) 1, 3, 5
range(3, -2, -1) 3, 2, 1, 0, -1
range(10, 0, -4) 10, 6, 2
Example 3.2
Two programs printing all integer multiples of 5 less than 50 (Notice the compactness of the for
construction compared to the while).

# For loop condition using # While loop implementation of printing


# range() function to print # multiples of 5 less than 50
# all multiples of 5 less than 50 # Initialization
for i in range(0, 50, 5): i = 0
print(i) # Limiting the range to be less than 50
while i < 50:
print(i)
i += 5
Output:
Output:
0
0
5
5
10
10
15
15
20
20
25
25
30
30
35
35
40
40
45
45
Exercise 3.7: Counting spaces
Write a program using a for loop that takes in a string as input and counts the number of spaces in the provided string. The
program must print the number of spaces counted.

Example: If the input is "Hi everyone", the program outputs 1.

# 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.

Enter the first number:2


Enter the second number:8
# Sample output
Even numbers: 2 4 6 8
Odd numbers: 7 5 3

You might also like