Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.8.2 While loops
While loops nesting
Basic Overview
Nesting is a term used when we use multiple loops inside of each other
Used when you want to you a loop multiple sets of times each set with different values
Many other versatile uses
Pseudocode Example
initialize outer_counter to 0
initialize inner_counter to 0
while outer_counter is less than 3:
print "Apple"
while inner_counter is less than 5:
print " Banana"
increment inner_counter by 1
reset inner_counter to 0
increment outer_counter by 1
Python Example
outer_counter = 0
inner_counter = 0
while outer_counter < 3:
print("Apple")
inner_counter = 0
while inner_counter < 5:
print(" Banana")
inner_counter += 1
outer_counter += 1
Apple
Banana
Banana
Banana
Banana
Banana
Apple
Banana
Banana
Banana
Banana
Banana
Apple
Banana
Banana
Banana
Banana
Banana
Javascript Example
%%js
let outerCounter = 0;
inner_counter = 0
while (outerCounter < 3) {
console.log("Apple");
innerCounter = 0;
while (innerCounter < 5) {
console.log("Banana");
innerCounter++;
}
outerCounter++;
}
<IPython.core.display.Javascript object>
What is Happening
First, we initialize two different integers
Then we begin our first loop that will run until outerCounter greater than or equal to 3
Then we print out “Apple”
Then we set innerCounter to 0
Then we begin our second(nested) loop that will run until innterCounter is greater than or equal to 5
Then it prints out banana and increases the innercounter by one
Then in the first loop we increase outercounter by 1
this will lead to an output with 3 sets of
Apple Banana Banana Banana Banana Banana
Popcorn Hack #2
Create a piece of python code that prints out your name one time
then after printing your first name one time, print out your middle name 2 times
and finally print out your last name three times
this entire thing should be repeated 4 times
</img>
–>