Python for Absolute Beginners Transcripts
Chapter: Organizing and reusing code with functions
Lecture: Concept: for-in loops

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's review this idea of for in loops. The for in loop is excellent for going through a collection of items. This is extremely common in programming.
0:11 In programming you'll be given a bunch of stuff and you're like, well, I have to go through each one individually and do something with it.
0:16 Maybe the user typed it in. Maybe it's a file, you want to go through every line. Maybe it's something you got off the internet.
0:22 You call some API and it sends you back a bunch of data. Who knows what it is? But you go through them always the same way.
0:28 So here we have plays, which is a collection a sequence with three items: rock, paper and scissors. We want to go through each one
0:36 and show them to the user. Here we're going to actually print them on the same line, so there's this cool trick we can do with print and we can say end
0:43 instead of being a new line a line break, it can be a space. For each time we do a print statement it just piles up on the end as a space.
0:51 You could put comma you could put a dash, whatever you want. So we're going to say for p in plays. We're going to print that out.
0:59 Rock and then paper and then scissors. That's pretty cool. But a lot of times we need to actually know the number.
1:04 Like, we're asking the user, enter one, two, or three and then that will correspond to rock, paper or scissors.
1:11 So if we want to do that, we go and have the same for in loop but we use the enumerate keyword and we can control the start position.
1:18 Talking to humans, usually start equals one. If you just need to know the index in the list then leave it alone, you'll get zero, one, two, three.
1:26 And then we have two elements that come out into our loop there, so we say four idx comma p so index and the play is going to come out
1:35 and then we can work with them both at the same time. You'll see these loops everywhere. They're super, super common.
1:41 They're the other type of loop that you have in Python other than the while loop. While loops are great for I want to do a condition
1:47 as long as something is true but for in loops are super powerful because they let you take a collection of things
1:53 and work with them, each one of them individually.

Talk Python's Mastodon Michael Kennedy's Mastodon