For Loops & While Loops in Python - Beginner Python Tutorial #5 (with Exercises)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys and welcome back to the fifth episode of my Python tutorial series in this video we are gonna go over four and while loops which are two different ways to repeatedly execute blocks of code also I want to mention that once you finish this video you'll have enough skills to build a basic game in Python so make sure you look in the description for a link on how to build this game that I'll show you right now basically it's a simple game where you're controlling the red block by moving the left and right arrow keys and these blue blocks are falling and you're trying to dodge them and basically the score goes up each time you've successfully dodged a blue block it gets to the bottom and as the score increases the blue blocks start falling faster and faster and if I ever do collide with a blue block it says down here game over your score so this is the game that we will be able to build once you finish all the things that would cover in this video all right let's get started all right let's begin with the for loop so let's say I wanted to print out the words hello world ten times but I didn't want to just type out you know print hello world and copy and paste that ten times just like that's kind of annoying so we can use a for loop to simply to simplify this for us so what I can do instead of just copy and pasting is I can do for I in range 10 and then make sure you end this forced it for loop with a colon and then I can just do print hello world and I run that and as you can see down below it printed out hello world ten times just like I wanted all right so that's just a basic example and I can change this to whatever value I want so range is how many times you want it to loop through so if I did it a hundred times you see that I have a hundred dollar where else now it does it really really quickly it's worth noting that in this statement so if I go back to range ten so in the statement this I variable right here represents what iteration we're on so I could do something like print I instead and if I did for I in range 10 and then I printed I it's going to print out the numbers 0 through 9 and it starts at 0 the main reason that starts at 0 is just like indexing we count we count starting from 0 in Python but it does include 10 iteration so 0 through 9 is 10 total 10 right here is the first number that we don't include so we can print out I and we don't just have to do print statements in here we can make this more complex so let's say I just wanted to print out odd numbers for example so I just wanted to print out odd numbers I could do something like if I mod to so this means like divided and check the remainder equals equals one so that would make it odd do a colon two because whenever we have something inside we always have to use a colon and indent and then I'll do we don't have to use an else but I can do an else else we'll just do nothing just we can write this pass word as you can see there 1 3 5 7 and 9 so we can make our four loops a little bit more complex but this eye is just like a placeholder so if I instead is this is just like variables you know we can call whatever we want is just going to be holding the variable for us so like when we were writing functions and we passed in a variable to the function name this is the same thing it's just a placeholder so I could call this like cactus for cactus and range 10 print cactus and as you can see does the 0 to 9 just like we had for when we just did print I one of the most useful reasons we use a for loop is to iterate through lists so as you should have learned in the last video about lists we can declare lists such as a grocery list by doing the following use these two brackets and then insert our items inside so let's say we wanted milk toast eggs and avocados so that's our grocery list instead of doing for cactus and range 10 I would actually change this to in grocery list for cactus in grocery lists and cactus does not make the most sense to use here so we're going to just say for item in grocery list it doesn't matter what we call it as long as we use the same value inside the for-loop so for item in grocery list this will take the list defined by the grocery list and just take the first element then the second element then the third element and then the fourth element and each time we get a new element we can access that element by this right here so if I run this as you can see milk prints out my online toast prints out online eggs prints out of one cut line and avocadoes prints out on one line so this iterated through a list and we don't have to just use you know words we can also do this with numbers so let's say I wanted to pass in some weights so I'm I'm gonna just I took this this information from online but I'm passing in the weights of some players on a professional sports team and bonus points to the person who watches this video and can figure out which sports team these values are coming from so here are the values so we have weights these are the weights of all the players on this sports team as you can see there's a bunch of them what we can do with that is we can iterate through each weight in that list with this for loop so for wheat in weights and if I print out the weight as you can see below it grabs each of want each one of them and it prints it out on a new line all right so this is cool but we're usually going to want to do something more complex than simply then simply print out like a single value we want to do something with these values so for example let's say we wanted to find the average weight of a player on this team so if I did average weight so how do we calculate average weight so if I was doing this mathematically I take each one of these values and weights add them all up and then divide by the total number of weights there are so what I can do is I'm going to define a variable called total weight outside of this for loop and total weight before we take any of these numbers from the players it's just going to be set to zero what we're gonna do is on each iteration we're gonna add the weight that we're currently looking at so in the first iteration we would add 208 to our total weight so I can do total weight equals total weight plus weight so this takes our cumulative sum and adds the one we're currently looking at to it and then if we get to the bottom I'm just going to print out total weight and the total weight of all these players is just under 5,000 pounds so if you ever to line them all up squish them together and put them on a scale that's what the team would weigh so and also worth noting is I don't have to do total weight equals total weight plus weight there's actually a shortcut to do this command and that is plus equals so instead of doing total weight equals total weight plus weight if I just do total weight plus equals weight it takes whatever total weight was set before and adds weight to it and then resets it to total weight so if I run this it's still the same thing all right and then to get the average weight of a player we just need to know the total number of weights there are in this list and from the last video you might remember the command length le n so we can use the command number of players will call equals length le n of the weights variable so now if I print out number of players we have this amount of pounds for this amount of players and finally what we wanted to do was the average weight of a player on this team and we can do print total weight divided by number of players so this is a useful way we can kind of use statistics use Python to aid in our statistics so the average weight of a player on this team is 109 nine pounds and we can easily adapt that you know keep going farther I'm gonna not do it in this video just for the sake of time but we could keep going we could find the standard deviation of a dove this process also I want to mention real quick that this method that we did right now does for weight and weight and it grabs the individual weight so if I was printing out each weight you should have seen this before but I'll do it again it going from the top starts with 208 then 221 just as this goes another way to do this is by instead of using the actual weight we find the index in the range of the length of weights so what I'm doing right now is instead of directly grabbing this toy I'm instead just setting an index that will contain all the indexes in however long this weights is so now I can print out index and this is going to give me there because I didn't define weight now they say weight is zero for now don't worry about this so but what you can see is I'm printing out the index it's counting 0 to 24 which represents the 25 positions a player can have in this graph and what we can do is with that index we can grab a weight as follows we can do total for weights that's the list of the weights and then do brackets and then index so we're grabbing the weight that is found in the index position so when this is 0 on the first iteration we grab weights 0 and that is 208 so this is just another way to do the same exact thing we just I just showed you before and sometimes this can be a useful way to do it now always but it is good to see that you can do this method and just grab the indexes and then set it down here so now if I run this we have that same value we had before and just keep note of this because maybe we can use this in the end of the the video you'll need to grab multiple indexes at the same time so if we do it this method we can do like weight - equals weights of index plus one and we can grab two different weights at the same exact time so just note this method before I finish with for loops one of the advanced methods that I guess it's not that advanced but one thing that is this help helps me a lot when I may be iterating through an Excel spreadsheet is using this enumerate keyword so if I use this enumerate keyword I can grab the index and the weight at the same time it gives me both so I do like index comma weight that will give me the index of this position and also the actual value at that position which is sometimes helpful to to know both of those things so if I do that and I print index and then I print weight and I run it down here you should see zero-two ou812 21 so this is a numerate key where it allows us to get both the index and the weight all right let's move on to wild loop so I'm going to delete all this code here alright to introduce wild lips basically think of a while loop as an if statement that repeatedly checks itself over and over again so if I did something like if true let's just say then I printed like hello world right and I ran that it would just print out that hello world one time a wild state a while loop however does the following so I did while true hello world this is basically like plain English like what would you think would happen while something was true and you had it inside that it just repeatedly prints out hello world so you can't let me change up this example a little bit so you can see more visually but I printed hello world and then hi again two different lines you see that it just is continually running these these two print statements over and over and over again and that's going to keep happening until this true becomes false so to show you an example where that type of thing would happen I'm going to cancel this real quick so if you're go to tools you can cancel a a while loop if it's infinitely running this is called an infinite loop you can cancel it by going into your tools and then cancel build or control slash break control + play break or command + + + I literally can't talk right now command + break if you're on a Mac so let's imagine this is just like a for loop so in a for loop we can count to 10 we can also do the same thing in a wild lip so let's say I said what I equals zero while I is less than 10 print I and then we did I plus equals one so I ran this I print out zero through nine because it keeps printing out I when it's less than ten and because we keep adding one two I each iteration eventually it will get to ten and this statement right here will be false so I could also like print out I less than ten so you see how execute is true all the time here and if I and it didn't execute that last one that's false because if this is true or this becomes false it doesn't execute any of the code inside all right so that's counting to ten with a while loop one of the major reasons I guess a while loop is used is to deal with these boolean conditions so if we're developing a game we might have a variable called game over right and that's initially set to false so we could have a while loop running they would continually run and execute our gameplay code while we're not at the game over condition so I just print playing game here I never run that you see it just keeps I can scroll up and it keeps playing the game this just is happening non-stop so let's imagine in addition to playing like in addition to having this not game over a condition we had a score and let's say the goal of this game was to get to 100 so if our score is initially set to 0 let's say this is a super fun game you know each iteration you get a a random value so if we import random this the score at each iteration is just going to be some random integer that we add on to the score so score plus equals random end and let's say it's like 1 through 10 so if you don't remember a random and on randon this is something I showed in the math and variables video the first actual tutorial and I'll print score and I'll say if score is greater than 100 game over equals true so watch what happens here so our score just keeps increasing then finally it hits 102 102 is the first value that is greater than 100 so this variable becomes true and we exit out of this while loop so while loops help us like control flows based off a certain boolean condition so this game over because it's true or false it's a boolean condition before we finish up with the explanations of what loops are and we actually move on to two examples using loops I want to quickly go over two more things and that is the break statement in the continue statement so imagine we had in addition to this code right here we had a line that just said game is still on right and this could be anything maybe this is game crucial code right down here and it comes out for this if score is greater than 100 but note that when this game is over at 105 so the game over is true right there at this 105 block it still prints out game is still on so it could be still printing out or executing this game game code so we'll use the break statement if we want to just quickly exit out of exit out of a while or for loop this works with both for loops and while loops so I could do break and then if I reran that you see how 105 is the last value but it does not print this game is still on here so it exits out of the while loop so it would exit out and go to whatever line is at the first indent so if I printed you lose here or actually maybe you win let's say you win see that it doesn't print the game is still on but it does print this you win all right so that's the break statement it exits out of a four or a while loop really quickly so right when it's hit then you're out of the loop the other statement is the continue statement so maybe a better way to see the continue statement is if we had in addition to score is greater than greater than 50 we had a walk that was if score is less than 50 and I wanted to just write continue and then down here I'm gonna leave this break but I'm gonna print out some code that just says you are getting close to winning so what this continue statement is gonna do is during the first few iteration so we got 2 3 13 20 23 29 31 to 36 46 50 doesn't print out anything but then once we hit 50 it says you're getting close to winning 53 says you're getting close to winning so what this continuous statement did is it exits out of the loop but it exits out to the top of the loop so it it doesn't run any of the code down here but it run goes back to the top so the difference between the continue statement and the break statement is that the continuous statement goes back up top to the next iteration of the loop the break statement exits out of the loop so you'll find uses of these different statements throughout your like well as you get more experience with these loops I just want to introduce them so you knew that they existed okay let's finish this video off with two examples on the coding bat website that I've introduced before so we'll do I'm gonna drag in the coding bat site come on so we're gonna do coding back Python and we're gonna do the warm-up two exercises so the first exercise we're going to do is called string x so try this exercise on your own and then if you can't figure it out I'll do it once you impose the video okay to do this first exercise we need that we note that whatever is in here we need to be repeated this many times so the amount of times we need to repeat something we'll use a for loop for that so I'm going to do for I in range and colon and then I will do print string right because that's how many times we want whatever oh my got to keep doing ctrl s but if I use this site that so many times we want to print out whatever strings in here and that's represented by this variable and then the amount of times is represented by the very well so if I run that it says don't print compute and return or result value so remember whenever you use a function we don't want to print we want to return a value so I'm going to do a return string this actually doesn't work as you can see every time here in the run code it just does it one time so we don't actually want to return the string what we want to do is we want to set a string like we'll call it final string that equals we'll just say that's empty at first when I just say control this again so final string is s empty each time we run this loop we want to add on the string that we're gonna print out at the end to the final string so final string plus equals and I might have not have mentioned this before but you can add together you can concatenate strings using the plus the plus operator so just like you can add number to knotted strings but adding string just means putting like two words together so final string plus equals the string and then if I return that and I don't want to return it in this for loop because then it will return on the first execution I want to actually go outside the for loop and return it once the for loop is done so I'm gonna do final string and click go and everything works for that so start out with a blank string you run a loop that iterates n times and each time you append or I guess you're not really a pen but you add on a new string so that when you get to the end of the loop you have that string repeated n times cool okay let's do one more exercise we're gonna do beret one two three this is going to be a pretty hard problem array one two three so don't feel bad if you can't figure it out and pause the video and when you're ready to see the solution on pause alright to solve this problem we are given an array of int and we want to return true if the sequence of numbers 1 2 3 appears in the array somewhere so this is where we're gonna have to use that indexing that I show you when we were going through the player weights example earlier in this video so we have this array and if I just went ahead and printed let's say we had a loop and we're iterating through each number in the loop I just did for number in nums for num nums print num and I'll just return at the end return this will just just so it doesn't yell at me I'm just returning this this is not actually gonna work yet don't print I won't even let me okay it doesn't even let me print that's annoying but so if it if you're trying to test this and it's you having trouble because it won't leave print what I recommend you do is you can actually just copy this code and put it in your sublime text window so I'm deleting all this and I'm pasting it in here so for num nums i want to print num and i'll take one of the examples they gave me so we'll take this last example because this last example is a true example so we got this is our nums and we have the function definition now we need to actually call the function so we're in the array one two three of nums and as you can see we're printing out each value in that list by just doing what we have here so the tricky thing is is in this problem we need to keep track of three numbers at the same time because we're looking for one two three so what we should do instead of doing for num nums we should do for I in range nomes and what that allows us to do is we can do something like first value equals nums I that's the I index second value equals nums I plus one so that would be if this I was 0 we'd have 1 + 0 plus 1 would be the first index so that would give us these two values then finally third value equals nums I plus 2 and basically what we're checking is if first value equals equals 1 and second value equals equals 2 and third value equals equals 3 then we want to return true right and if that never happens then we know at the end of this week and so where this statement is so after the loop is done we can return false if we brought that list object cannot be interpreted as an integer so I can do length knows so before I was trying to take the range of a list I need to actually take the range of the length of the list we're trying to take the range of run that and we'll actually print out this page so we'll print out to see if it says true or false true cool so it read that we had the 1 2 3 here because we got the three indexes and the one thing to note with this is we're still not done because if I ran this function into our coding bat so it's actually gonna give us an error so see if you can figure out the error so it says list index out of range and the reason we have the error is when we get to the last index so let's say we were looking at this bottom example again or maybe that's say we were looking at this middle example in this middle example we don't actually have a one two three we have one one two four one so we would iterate starting at this element then go to this element then go to this element then go to this element and then so when it got to this element the first value would be four second value would be one but then we're trying to get the third value using this line right here and there wouldn't actually be enough list get that third value so this line right here would cause us an error so what we actually have to do is do length nums minus two because we want to stop right at this the last time we can get three elements in a row because we don't need to check any farther so you want to stop three before the end so in this case we'd stop in this element this one we'd stop at this element and this one we'd stop at this element so if I run that yeah we got it to work cool all right that's all we're going to cover in this video hopefully you learned what for loops and while loops are if you have any questions still leave them down in the comment section and also make sure to check out that game I showed you at the start of this video so the game that looked like yes Wow where is it where the game guy oh yeah so make sure to check out this game there'll be a video on how to build that in the description alright thanks for watching guys make sure to LIKE this video if you learned something and also subscribe so you don't miss the next tutorial which I'll be posting sometime next week peace
Info
Channel: Keith Galli
Views: 37,667
Rating: 4.9461884 out of 5
Keywords: KGMIT, Keith Galli, for loops, while loops, python 3, python programming, python, for loop in python, python tutorial, exercises, examples, python practice problems, python exercises, beginner python tutorial, learn to program in python, how to code, python for kids, kids, simple, easy, beginner, python tutorial with examples, python study tips, how to get good at python, how to program in python, best python tutorial, easy python lessons, lessons, 2018, loops in python, loop, for, while
Id: WPF5M_Ic6Fc
Channel Id: undefined
Length: 31min 25sec (1885 seconds)
Published: Wed Mar 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.