Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.8.1 While loops
Basic concept for while loops
Basic Overview
While loops are consisted of two main componenets
The condition ex: x > y, or y > 8, or string = “xyz”
The inside code: This could be anything that you want run
What happens?
The inside code is run an infinite amount of times until the condition is equated to false
note that if the condition is met halfway through the inside code, the rest will still be accomplished
Pseudocode Example
# Initialize a variable
counter = 1
# While loop starts
WHILE counter <= 5 DO
# Print the current value of the counter
PRINT "Counter is: ", counter
# Increment the counter
counter = counter + 1
# End of the loop
END WHILE
Python Example
# Initialize a variable
counter = 1
# While loop starts
while counter <= 5:
# Print the current value of the counter
print("Counter is:", counter)
# Increment the counter
counter += 1
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
Javascript Example
%%js
// Initialize a variable
let counter = 1;
// While loop starts
while (counter <= 5) {
console.log("Counter is: " + counter);
counter++;
}
<IPython.core.display.Javascript object>
What is happening?
In both of these examples we are declaring an integer called counter and setting it equal to one.
Then our condition for these while loops is if counter <= 5.
This means that our code will run until counter is greater than 5
Then the inside code prints to the terminal “Counter is: “ then it adds the integer of counter, then increases the value of counter by one
Popcorn Hack #1
I want you to create a while loop that will print out “hello” to the terminal 5 times
Example
counter = 5
while counter < 0:
print("Hello")
counter -= 1
–>