Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
10:14

Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops

Corey Schafer 17.05.2017 1 036 893 просмотров 24 309 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Beginner Tutorial, we will begin learning about Loops and Iterations. Specifically, we will be looking at the for/while loops. We will learn about iteration and also how to break out of the loops using the break and continue keywords. Let's get started. The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Loops Watch the full Python Beginner Series here: https://www.youtube.com/playlist?list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7 ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (3 сегментов)

Intro

hey there how's it going everybody in this video we'll be learning about loops and iterations specifically we'll be going over for loops and while Loops now we've seen Loops a couple of times in our previous videos when looping through strings or lists but there's some more functionality that we haven't gone over yet uh that we'll see in this video but first let's just do a quick recap so we've got a list of numbers here with numbers one through five so let's Loop through this list so to do this we're going to use a for Loop so we'll say for

For Loop

num in nums and within here I'm just going to print out that num so what we're saying here is that we want to create a loop where We're looping through each value of our list and each time through the loop this num variable will be equal to the next item in the list so the first time through it'll be equal to one the next two and so on so if we run this we can see that it looped through and printed each number of our list so now let's look at two important keywords when working with loops and these are the break and continue keywords so the break keyword will completely break out of a loop and the continue keyword moves on to the next iteration of the loop so first let's look at the break statement so let's say that we are looking for a certain number in our list and once we find it we don't need to continue looping through the rest of our values now this is when the break statement comes in handy so let's say that we're looking for the value of three so I could come in here to our list and I could say if num equals 3 then within this uh conditional we'll print out that we found it and then we will break out of that Loop so now let's go ahead and run this so we can see that it looped through the numbers one and two but it didn't hit this conditional when the num equal one and the num equal two and since those first two values didn't meet this conditional then it didn't print out found and it didn't break out of the loop but when it got to number three it did meet this conditional so it printed out found and then our break statement broke out of the for Loop and when it you can see that we didn't iterate through any more values so we did not get through to values four or values five now notice that we broke out of our Loop before we printed the number so the three never got printed out but if our print statement were Above This conditional then the three would have been printed out so the break statement breaks out of the loop but what if we wanted to just ignore a value but not break out of the loop completely so to do this we can use the continue statement now continue will skip to the next iteration of a loop so if we replace this break statement with continue uh and run this so we can see here that just like before the first two times through with one and two it didn't meet this conditional so it didn't do anything within this if block and it just printed out our number but when we got to the number three it did meet this conditional and it came in here and printed out found and then our con continue statement just skipped to the next iteration without coming out here and printing out the number three so as soon as we hit continue then it just went to the next iteration which was four and five so when four and five ran through they didn't meet these conditionals and it just printed out the number so it's important to understand the break and continued statements and the differences between those because there's a lot of different use cases for when they come in handy to solve certain problems okay so now let's look at something that we might run into which is a loop within a loop and this is possible so within our Loop here I'm going to replace this conditional with an inner loop so now I'll say four letter in and I'll just uh make a string here of ABC Now within this inter Loop then I'll just go ahead and print out num comma and the letter so now what's going to happen here is that for each number it'll Loop through every character in this string and print out the number and the character and then move on to the next number and do it all over again so let's run this and see what we get so now let me make this just a little bit larger here so now we can see that what happened is that for one it looped through every letter in the string and then after it finished that inter Loop then it moved on to the next number before doing the exact same thing so we have 1 a 1 b 1 C then it moved on to two 2 a 2 b 2 C and so on so what this really did is it gave us every combination of those numbers and characters now you want to be careful with nested list because these combinations can grow pretty quickly so if you have tested loops with a lot of different values then it may take a while to Loop through all of those different combinations okay so something

While Loop

that we'll probably run into a lot is that there's going to be times when we just want to go through a loop a certain number of times and there's a built-in function called range that is really useful for this so let's say that we wanted to just run through a loop 10 times so to do this we can just say 4 I in range 10 and with in here we will just print out I so now if we run this then we can see that it just prints out 0 through 9 which is 10 items so we start at zero and go up to but not including this number that we passed into range now if we don't want to start at zero then we can also pass a starting value into range so if we wanted to start at one and print out the values 1 through 10 then what we could do is say that we want to start at one and now we're going to have to go up to 11 because it doesn't include the last value so now if we run this then we can see that now it started at one and goes up two but not including 11 so 1 through 10 okay so now let's take a look at while Loops so our for Loops iterated through a certain number of values but while Loops will just keep going until a certain condition is met or until we hit a break so for example let's say that we had a variable here of xal to0 and now we can say that while that X is less than 10 then what we want to do is just print out X and then we will iterate X by 1 now we have to remember that this Loop is going to go on forever until this condition here evaluates to false so if we want this Loop to end at some point then we have to remember to increment this X so that at some point it will be greater than or equal to 10 so that it breaks out so now if we run this then we can see that it prints out 0 through 9 so it came in and saw that x was 0 Which is less than 10 so it goes through the loop prints the value and increments X by one now X is equal to one and it does this check again so one is still less than 10 so it stays in the loop and it does this until we increment X from 9 to 10 and then it'll come in here and make that check and it checks if 10 is less than 10 which it doesn't um which evaluates to false so it breaks out of that Loop now at any point you can just use a break to break out of the while loop just like we did with the for Loop so if I came in here and I said if x is equal to five then we just want to break out so if we run that then we can see that it went Z through 4 and once X was equal to 5 then we hit that break statement now sometimes you'll just want to create an infinite Loop That Never Ends until we get some input or find some value now to create an infinite Loop you can just replace the comparison that we're doing here with a value of true so now that we have an infinite Loop there's no conditional here that can break out so now we have to have this break statement in here if we ever want to stop this Loop so if we run this then we can see that we get the uh same output there now in this example we're using a conditional but this is also how you would keep a loop going indefinitely until you find or receive values that you're looking for now if you ever accidentally get stuck in an infinite Loop then within most environments or operating systems you can interrupt that by pressing controll C to stop the process so if we comment out our conditional here with the break statement then this is going to get stuck in an infinite Loop and just go on forever so now if we run this code then we can see that we get stuck in this infinite Loop where it just keeps incrementing X by one and printing out X now to get out of this on most operating systems you can press contrl C and it'll interrupt that so I you can see that it was cancelled and if you are in your terminal or command prompt then cons uh control C should send a keyboard interrupt okay so I think that is going to do it for this video I hope that now you have a clear understanding of the different loops and how the break and continue statements work in the next video we'll be learning how to write functions but if anyone has any questions about what we covered in this video then feel free to ask in the comments section below and I'll do my best to answer those um if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to Simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Методичка по этому видео

Структурированный конспект

Циклы и итерации в Python: полное руководство по for и while

Подробный разбор циклов for и while в Python: итерация по спискам, операторы break и continue, вложенные циклы, функция range и бесконечные циклы.

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник