We have just learned about while loops. Let's move on to another type of loop in Python, the for loop.
The example we used in the last lab to print "meow" took a bit of set up. We had to create a count variable and ensure we incremented it in the loop.
Without these two extra lines of the code the loop would not work.
It turns out, that for counting purposes, that a for loop is a bit easier to set up and use.
This does the exact same thing. It still creates a variable "i" and increments it. The process is just a bit more streamlined.
The range function can also take parameters for min, max and increment. Here we make a loop that counts from 15 down to 0 by 5's.
We will learn more about for loops another time, but for now another powerful example of how they can be used with strings.
Instead of looping through a range, we loop through a string.
Complete the following requirements:
Use a for loop to print the numbers from 1 to 10.
Use a for loop to print the numbers from 10 down to 1.
Ask the user for an integer 'x', and use a for loop to print all numbers from 1 up to 'x'.
Ask the user for an integer 'y', and print out the multiplication table of 'y' for numbers from 1 to 12.
Press Ctrl + F5 to run the program or open a terminal and type python lab2.py
You should now know how to create and use for loops in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 2 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.