For Loops

Flash and JavaScript are required for this feature.

Download the video from iTunes U or the Internet Archive.

Description: This in-class question demonstrates For Loops and Break statements in Python.

Instructor: Dr. Ana Bell

The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To make a donation or view additional materials from hundreds of MIT courses, visit MIT OpenCourseWare at ocw.mit.edu.

PROFESSOR: So now we have this last exercise. I'm creating a mysum. I'm going to go through all of these values and you guys have already told me what values these are, 5, 7, 9, not 11. And I'm going to add to mysum. So I'm going to keep a running sum adding all of these values together.

So the very first time through the loop, mysum gets the value of 5. That's this line here. The next thing I see inside this loop is an if statement. If mysum is equal to 5. That's true. So I'm going to go inside this if statement. The next thing I see is a break.

If I see this break am I evaluating-- am I evaluating this line or not? No, exactly. Because whenever Python sees break, it's going to say, I'm going to stop right here, exit out of the loop that I'm currently in, and go to the statement that's immediately right after it.

So what this is going to print is mysum. And that's the exercise we were looking at. Let's see how the class did. Pretty good. Hopefully if you answered one of these, the explanation was-- was all right. If not, just go back and try to work through it step by step.

Free Downloads

Video


Caption

  • English-US (SRT)