So far we have learned how to work with text, numbers and conditional statements. Let's move on to how to repeat things in Python.
Ensure that you are signed into GitHub
Open the assignment: Project 3 - Guessing Game
Clone the repository to your computer using GitHub Desktop, or open it online using Codespaces
Open lab1.py
Sometimes we want to repeat things in code. Let's say we want to make a cat "meow" 3 times:
Easy. But what if it was 100 times or 1000 times? Or what if we want the user to specify? This method is not sustainable.
Enter the concept of loops. Loops are a control structure that allows you to repeat a certain block of code.
while loops contain a condition, much like an if statement. In the example below "meow" will repeat while count < 3 is still true.
This ability to repeat the code while a certain condition is true is very handy. E.g. while password is incorrect, keep entering password.
Of course, you can combine while loops while conditional statements to make them even more useful.
Complete the following requirements:
Create a while loop that prints the numbers 1 through 10.
Create a while loop that prints the numbers 10 down to 1.
Write a loop that continuously prompts the user for a password until a predefined password is entered.
Write a loop where the user can enter numbers continuously, and the program prints the running total.
Press Ctrl + F5 to run the program or open a terminal and type python lab1.py
You should now know how to create and use while loops in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 1 complete"
Press Commit to main
Press Push origin
Here is a video from Harvard's CS50P course that covers the content of the this lab. Optional, but useful if you need further explanation.