Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.8.2 While, Do-While (P2)
Student led teaching on Iteration. Learn how to do loops with Java and Python.
While Loops
A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true.
The loop will continue to execute until the condition becomes false, at which point the loop terminates.
A working while loop has three key components:
- Initialization of the loop control variable
- Actions or operations performed within the loop
- Update of the loop control variable to eventually meet the termination condition
The loop evaluates the condition before each iteration, so if the condition is false at the start, the loop’s body may never execute.
While Loop Using Python
# Initialize the control variable
number = 1
# While loop that runs as long as the counter is less than or equal to 5
while number <= 5:
print("Number is:", number)
# Update the control variable (increment by 1)
number += 1
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
While Loop Using Javascript
%%js
let i = 10; // Initialize a variable
while (i >= 0) { // Condition: loop runs as long as i is greater than or equal to 0
console.log("Countdown: " + i); // Output the current value of i
i--; // Decrement the value of i
}
console.log("Liftoff!"); // Message after the loop completes
<IPython.core.display.Javascript object>
While Loop Popcorn Hack #1 (Uses Javascript)
- Generates and prints all even numbers between 1 and 20.
- It’s a handy loop for quick number generation with minimal effort.
number = 1
while number <= 20:
if number % 2 == 0:
print(number)
number += 1
2
4
6
8
10
12
14
16
18
20
Do-While Loops
A control flow statement that executes a block of code at least once. It will continue to execute
the block repeatedly, or stop, depending on a true/false condition evaluated at the end.
A working loop has three key components:
- Actions or operations performed within the loop
- Update of the loop control variable (flag)
- Test expression to determine whether the loop continues or terminates
Do-While Loop Using Python
# Initialize a variable
count = 0
while True: # Infinite loop to mimic 'do'
print("The count is:", count)
count += 1 # Increment the count
# Check condition at the end (like in a do-while loop)
if count >= 5:
break # Exit the loop when the condition is met
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
Do-While Loop Using Javascript
%%js
let count = 0;
do {
console.log("The count is: " + count);
count++; // Increment the count
} while (count < 5);
console.log("Loop is done.");
<IPython.core.display.Javascript object>
Do-While Popcorn Hack #2 (Uses Python)
- Simulates flipping a coin until it lands on “heads” using random generation.
- It’s a simple hack to simulate random events.
import random
flip = ""
while flip != "heads":
flip = random.choice(["heads", "tails"])
print(f"Flipped: {flip}")
print("Landed on heads!")
Flipped: tails
Flipped: tails
Flipped: tails
Flipped: tails
Flipped: heads
Landed on heads!
Homework Assignment: Advanced while and do-while Loop Practice
Task 1: FizzBuzz with a Twist (while loop)
Objective: Create a modified version of the classic FizzBuzz game using a while loop.
Print numbers from 1 to 50.
For multiples of 3, print “Fizz” instead of the number.
For multiples of 5, print “Buzz” instead of the number.
For numbers divisible by both 3 and 5, print “FizzBuzz”.
Add a twist: for multiples of 7, print “Boom”.
Challenge: Change the range to numbers between 50 and 100 and modify the conditions to fit this new range (e.g., multiples of 4 instead of 3).
Task 2: User Authentication System (do-while loop)
Objective: Simulate a basic user login system with a do-while loop.
The user has 3 attempts to enter the correct username and password.
After each failed attempt, display how many attempts are left.
After 3 failed attempts, display a message saying the account is locked.
Use a do-while loop to handle the login process, prompting the user for their credentials until they either succeed or run out of attempts.
Challenge: Add functionality to “reset” the password if the user runs out of attempts, prompting for a security question.
Reflection: Loop Efficiency
For a reflection, consider loop efficiency:
When would it be better to use a while loop instead of a do-while loop, and vice versa?