The while Loop
Section 3
Chapter 3
1
Quiz 8 code: whoof
Time Limit: 10 minutes
2
Agenda
• while loop
• String methods returning Boolean values
• break, continue, infinite loop
• Classwork
3
Repetition Structure
4
Recall: conditions
• A condition is an expression that evaluates to either True or False.
• Conditions are used to make decisions
• Choose between options
• Control loops
• Conditions typically involve
• Relational operators (e.g., <, >=)
• Logical operators (e.g., and, or, not)
5
Recall: Relational Operators
The while Loop
• A repetition structure executes a block of code repeatedly
• A while loop repeatedly executes an indented block of statements
• As long as a certain condition is True
7
Example 1: Display numbers 1-5
• Displays numbers from 1 to 5.
• It would be tedious to use print(1), print(2), print(3), …
• We use a repetition structure instead.
• Other than for loops, we can use a while loop.
8
Recall: for loop
Example 1: Display numbers 1-5
9
Example1: Display numbers 1-5
Example 1: Display numbers 1-5
Q:What is the value of num when the program terminates?
11
Example 1: wrong solution
12
Example 1: Solution B
13
Example 1: Display numbers 1-5
• In the last iteration of Solution A:
• num=5 satisfies the condition.
• print(num) displays 5.
• num += 1 updates the value to 6
• In the last iteration of Solution B:
• num=4 satisfies the condition.
• num += 1 updates the value to 5.
• print(num) displays 5.
14
Example 2: Display odd numbers <=100
• Display all odd numbers between 1 and 100.
• Clearly, printing them one by one would not be wise.
• Use a while loop.
15
Example 2: Display odd numbers <=100
• What about displaying all even numbers between 1 and 100?
16
Example 3: Input validation
• Recall in HW5, we asked user to enter their marriage status using numbers 1 or 2.
• If users entered something other than 1 or 2, we can use a while loop to keep
asking users to enter the correct number.
17
Example 3: Input validation
18
String methods that return Boolean values
• Given: strings str1 and str2
• str1.startswith(str2)
• str1.endswith(str2)
• For determining the type of an item
• isinstance(item, dataType)
19
String methods that return Boolean values
20
Example 4: Input validation for
nonnegative integer
• One can use .isdigit() to verify whether the user has entered a
nonnegative integer.
21
Example 4: Input validation for
nonnegative integer
22
Example 5: Find max, min, average of a
sequence of numbers
• Strategy:
• Let the user enter numbers until s/he indicates there is no more number.
• Put all user-generated numbers in a list.
• Use built-in functions to find the max, min, and average.
23
Recall: List operations (max, min, sum, sorted, .sort)
24
Example 5: Find max, min, average of a
sequence of numbers
Do NOT flip the order of lst.append() and num = input() in the while loop.
25
Example 6: Compound interest
• Given an initial balance of 200,000 and a 3% annual interest rate,
calculate the number of years for the balance to reach 1 million.
26
Example 6: Compound interest
27
The break Statement
• When break is executed
• Loop immediately terminates
• Break statements usually occur under if statements
28
Example 7: display numbers
• In displaying numbers 24-100, suppose you want to stop
the program as soon as a number is divisible by 11.
29
Example 7: display numbers
• In displaying numbers 24-100, suppose you want to stop
the program as soon as a number is divisible by 11.
30
The continue Statement
• When continue is executed in a while loop
• Current iteration of the loop terminates
• Execution returns to the loop’s header
• continue is usually under an if statement.
31
Example 8: display numbers
• In displaying numbers 1-20, suppose you want to skip all
numbers divisible by 3.
32
Example 8: display numbers
• In displaying numbers 1-20, suppose you want to skip all
numbers divisible by 3.
33
Infinite Loops
• Infinite loops never ends.
• Can use Ctrl + c to force stop a program while running.
34
Example 9: infinite loop
35
else statement
• An else statement can also be added for while loops.
• The else part is executed once the condition in the while statement is no longer
True.
36
Kahoot
• Go to https://kahoot.it/
• Enter the game PIN as shown on the classroom projector.
• Enter your 8-digit student ID, E.g., 55123456
Do NOT use names.
• Kahoot is separate from the weekly quiz on Canvas. Kahoot
engagement (not merit) will partially determine class participation
scores.
37
Lab 8
38
Example A: Guess Number
Write a program that generates a random number between 1 and 100.
Prompt the user to guess the number. Provide hints (higher/lower)
until the user guesses correctly. Count the number of attempts and
print it when the user guesses correctly.
39
Example A: Guess Number
40
Example B: Prime Number Checker
Write a program that prompts the user to enter a number and checks
whether it's a prime number or not using a while loop. A prime
number is a number greater than 1 that has no positive divisors other
than 1 and itself (e.g., 2, 3, 5, 7, 11, 13, 17, 19, 23, 29).
41
Example B: Prime Number Checker
42
Example C: Palindrome Checker
Write a program that checks whether a string entered by the user is a
palindrome or not using a while loop. A palindrome is a word, phrase,
number, or other sequences of characters that reads the same
forward and backward.
43
Classwork 8: Ordinary Annuity
Assume you receive HKD 1000 at the end of every year, and the annual interest rate is 5%.
Write a Python program to calculate the time for the ordinary annuity to achieve a target
balance.
1) Let the user set the target balance.
2) Display the number of years for the future value to reach the target amount.
3) Use a while loop.
The output should be capable of the following and other target amounts. Follow the same
submission requirement (.py file and screenshot) as before.
44
Classwork 8: Ordinary Annuity
45
Homework 7
46
Homework 7
47
Homework 7
48