Introduction to While Loops
Welcome back to the fourth week of Intro to Code. We are going to be covering while loops during today’s class session.
The agenda for today is:
- Recap of If Statements, Variables, and For Loops
- Exploring While Loops
- Rock Paper Scissors AI
- Extended Learning Opportunities
Below are the slides to reference for today’s class:
Recap of If Statements, Variables, and For Loops
For this week’s coverage of while loops, you should be familiar with writing out conditionals (i.e. age == 0 or name == “Armando”), how if statements work, and what for loops are used for. If any of those seem fuzzy, feel free to jump back to previous material to review.
Exploring While Loops
While loops are way to repeat functions a certain amount of time until a certain condition is false. A really good example of this is rock paper scissors. You never know how long a game of rock paper scissors will take. But you know when to stop when 2 out of the 3 games has been won by a single person. In this case, if we were to write the rocker paper scissors game using code it would look as follows:
while 2/3 games not won yet:
play_rock_paper_scissors()
The above code is not actually Python code but it speaks to how while loops function. While loops are a mixture of if statements and for loops. Namely like if statements it takes a conditional after it. And like for loops it repeats functions over and over again. Below is another example of a while loop
age = 15
while (age > 20):
age += 1
In the above example, we notice two things, we will continue to run code until age is greater than 20. And we are actually changing the value of age as we go through the loop. Yes! We can change the values of variables. In this class we will show you how we can change number variable values. You can perform the following operations to number variables to change their value:
age += 1 #changes the age variable by adding 1 from it
age -= 1 #changes the age variable by subtracting 1 from it
age *= 2 #changes the age variable by multiplying it by 2
age /= 2 #changes the age variable by dividing it by 2
Rock Paper Scissors AI
For the rock paper scissors ai repl.it you will be using our helper functions to write out code to play a game of rock paper scissors against an AI bot. Note that the challenge to this exercise is to eventually get it to keep track of the score of how many games you win against the AI. For that you will need to use variables and conditionals as mentioned above.
Extended Learning Opportunities
For this week’s extended learning opportunities try taking a stab at previous Reeborg exercises that practice while loops along with getting a deeper understanding of how while loops work behind the scenes.