yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

for loops with range() | Intro to CS - Python | Khan Academy


3m read
·Nov 10, 2024

When we write a standard while loop, we need an assignment statement to initialize our loop variable to a start value and an assignment statement to update our loop variable on each loop iteration. In many cases, though, our loops are just counter-based, which means that the loop variable counts up or counts down on each loop iteration to repeat that block of code a fixed number of times. To save ourselves some work, we can instead write these as for loops, which is just an alternate syntax for counter-based while loops.

A for loop starts with a keyword for, then the name of the loop variable, the keyword in, and then the range function, ending, of course, with a colon. The argument to the range function is just the stop value for the loop variable, which tells the computer when to terminate the loop. This while loop and this for loop are now equivalent; they do exactly the same thing when executed.

Note that with the for loop, though, I didn't include these two assignment statements. I don't need to initialize my loop variable to a start value, and I don't need to update it on each loop iteration. The for loop statement takes care of all of that for us behind the scenes. That sounds like a lot of magic, so let's trace exactly what the computer does when it executes a for loop.

First, the computer simplifies down any expressions in the for statement. Here, it first evaluates this range function call. There is some nuance here to exactly how range works behind the scenes, but these are just details to optimize for efficiency. For our purposes, we should just think of range as generating a range of values between a start and a stop. By default, the computer uses zero as the start value. The stop value is the number passed into range; the start value is inclusive and the stop value is exclusive.

So this is really the range 0, 1, 2, 3, 4, stopping before it reaches five. On each iteration, the computer will set the loop variable to the next value in the range until it reaches the end, then it terminates the loop. So before the first iteration, the computer will assign the value zero to the loop variable pattern because zero is the first number in the range. Then it enters the loop body and executes the lines of code indented inside of it in order.

So it'll execute this print statement and then this print statement. When it gets to the bottom of the loop, as in the last line of code indented inside of it, it'll loop execution back to the top. Then it picks up the next value in the range and assigns that to the loop variable, so pattern now contains the value one. It enters the loop body again, executes this print statement, then this print statement, hits the bottom of the loop, and then loops back to the top.

It assigns the next value in the range to the loop variable, and then it repeats. Pattern now contains two, we do it again, pattern contains three, we do it again, pattern contains four. We execute the loop body one last time, and now when we loop back to the top, there are no more numbers in our range, so this tells the computer to terminate the loop. It skips the loop body and jumps execution to the next line of code outside of the loop.

So our for loop with range five repeated five times, once with the loop variable set to zero, to one, to two, to three, and to four. Okay, but what if I want my loop variable to start at a value that's not zero? The range function can optionally take another argument to specify the start. If we don't include it, the start value just defaults to zero. Here we now have the range from one to ten, so the loop variable would start at one, then two, three, so on until it gets to nine, which is the last value before our exclusive stop of ten.

Now that we can harness the power of for loops, why would we ever use a while loop? Well, all for loops can be expressed as while loops, but not all while loops can be expressed as for loops. For loops only work for counter-based repetition when we know up front how many times the loop needs to repeat.

If our loop condition waits on a program state that involves randomness or user input, we may not know up front how many times the loop's going to repeat. So we'll need a while loop to express that loop condition. But when we just need to repeat a block of code a fixed number of times, for loops are the fastest option because they collapse all the loop variable assignments into a single line of code.

More Articles

View All
Calculating weights on Mars with if-elif-else | Intro to CS - Python | Khan Academy
Let’s design a program with chain conditionals. We want to build a program that calculates an object’s weight on different planets. We have the formula for this already: weight equals mass times gravity. So, if we know an object’s weight on Earth, we can…
Plant reproductive success | Organism growth and reproduction | Middle school biology | Khan Academy
[Instructor] We’ve already talked about reproductive success in other videos. It’s related to the number of offspring an organism can have in its lifetime. And so in this video, we’re going to think about strategies that plants will use for reproductive s…
This Is What War Looks Like | Chain of Command
MAN: [inaudible]. MAN: They’re right here. They just went in this building. Enemy just went into this building. [inaudible]. CAPTAIN QUINCY BAHLER: Sayidi, I need them to say that nobody is in there. MAN: [inaudible]. CAPTAIN QUINCY BAHLER: Are there …
Part to whole ratio word problem using tables
We’re told that one month the ratio of indoor to outdoor play times for Yusuf’s class was two to three. They had 30 total play times. How many of the play times were indoors? How many were outdoors? Pause this video and see if you can figure that out. A…
Passing atmospheric levels of cool 🧑‍🚀🌏 #womeninstem #space
This is how many tampons Sally Ride was offered on her first space mission, which lasted about six days. Like a lot of STEM fields, NASA was male-dominated, and Sally Ride was their first female astronaut. After her death, we learned something very privat…
2015 AP Calculus AB 6a | AP Calculus AB solved exams | AP Calculus AB | Khan Academy
Consider the curve given by the equation (y^3 - xy = 2). It can be shown that the derivative of (y) with respect to (x) is equal to (\frac{y}{3y^2 - x}). All right, write an equation for the line tangent to the curve at the point ((-1, 1)). So, we could…