Learn the basics of for loops in Python.
Loops are one of the fundamental constructs that enable us to control the flow of our program. A for loop is a type of loop that repeats a block of code a specific number of times.
A for
loop in Python follows this structure:
The range()
function has a few default settings:
i
is 0i
is incremented by 1 each time.Take a moment to walk through the slides to see this in action.
Note that the value of i
goes from 0 up to but not including the number in range
.
A cool thing about the range()
function is that you can add parameters to customize your loop:
for i in range(initial, end, increment)
Initial is the starting value, end is the ending value (remember that this number is not included in your loop!), and increment is the amount i
is increased each time.
Take a look at the examples to see how you can use parameters to customize a for
loop.
for
loop to increase by 5 instead of by 2?for
loop to go from 10 to 100?Write a program that prints out the multiples of 5 from 5 to 30. You should use one for
loop with parameters. Your output should look like this:
As you can see, for
loops make our lives as programmers much easier by making it easy to repeat code a specific number of times. However, there’s so much more we can do with for
loops!
In Python, we can use for
loops to loop over strings, lists, tuples, and dictionaries. This comes in handy when we have data structures that contain hundreds, or even thousands, of items. The following code will loop over each letter in the string "karel"
and print each letter.
Similarly, this code will loop over a list and print each item in the list.
Explore these concepts by playing around with the examples below:
letter
to x
when looping over a string? Make sure to change both instances of letter
.my_string
to your favorite color. Make sure to keep the quotation marks! What happens?You are working at a sandwich shop. For each order, you ask the customer for their name and then spell it back to them to make sure the spelling is accurate. It turns out that you are an excellent speller and get their spelling right every time!
Write a program that uses a for loop to print out each letter of the customer’s name. You will need to create a variable for the customer’s name. You can jazz up your program by incorporating user input to get the customer’s name. To do this, just use the input(prompt)
function.
You’ve now mastered the basics of for
loops - congratulations! But don’t stop here, there is so much you can do with for
loops. You can combine for
loops with other control structures to create more complex programs.
Take a look at the example program below. Similar to letter frequency analysis, this program loops over a string and counts how many vowels there are.
Explore with these guiding questions:
for
loop?