For and While Loops in Python _ Databytes _ Python Basics Tutorial

**Loops in Python: A Comprehensive Guide**

If it's negative x equals x plus 2, in each iteration we still want to print the value of x if we run this we see that the first few iterations x is less than zero so it is added two and then on the final iterations where it is greater than or equal to zero it is added one. This demonstrates a key concept in programming: loops. A loop allows us to execute a set of instructions repeatedly, based on certain conditions.

A **while** loop behaves in much the same way as an iterative process. It takes the structure of `while condition: code` and then the code to run. In this structure, the condition is checked at the beginning of each iteration, and if it's true, the code inside the loop is executed. If the condition is false, the loop ends.

A **for** loop behaves in much the same way as a while loop, except it iterates over an editable object such as a list or dictionary. It takes the structure of `for variable in iterable: code` and then the code to run. In this structure, each element in the iterable is assigned to the variable, and the code inside the loop is executed for each element.

For example, we can write a basic **for** loop here, where we already have a list defined of words and we're going to say `for word in words: print(word)`. In this case, `word` is the variable name we're assigning to each element in the list. When running this, we iterate through each element of the list and print it out.

Another technique you may want to use is to print or run a loop a certain number of times and to do so, you can use the **range** function. For example, here we're going to write `for i in range` and then we pass in the number of times we want this to run. In this case, we want it to run five times, and we're going to print "This is a loop" and also print out the value of `i`. When running this, we iterate through each iteration, starting at zero because Python is zero-indexed.

You can also iterate over different types of Python objects not just lists. Here, we're going to iterate over each key-value pair in a dictionary using the **items** method. To do so, we write `for key, value in` and in the name of the dictionary, in this case, "countries". We then call the **items** method, and then we'll print the key and the value.

When running this, we've iterated through each pair in the dictionary and printed out the key and the value. You can also use the **keys** and **values** methods to print out the key or the value individually, rather than just returning both.

Another Python object you may want to iterate through is a pandas DataFrame, which is a two-dimensional data structure. It behaves in much the same way as the **items** method we just went over. Here, we have a DataFrame with country and population information, and what we're going to do is say `for index, row in` the DataFrame.

We'll access one column using the `df['column_name']` syntax, and we'll print out the value of that column for each iteration. When running through this, we've retrieved for each row the index and the data in the country column.

Sometimes, you may want to control a loop using advanced techniques. One such technique is to use **break** and **continue** statements. Here, we have a list of duck, duck, duck, goose, and what we're going to do is iterate through each bird in this bird's list and if the bird equals "goose", we are going to use the **break** statement to terminate the loop.

When running this, it iterates through each bird and as soon as it hits "goose" it ends the loop entirely. If you just want to end the current iteration, you can use the **continue** statement. Let's copy and paste our code from above but this time if it's "goose", we're going to continue, and when running this, what we find is that it runs through each element of the list and when it hits "goose" it ends the iteration and does not print the bird, which would be "goose" and continues on.

The final thing we're going to cover today is adding an **else** statement after a loop. This will run a selected block of code after every iteration is still complete. It will not execute if a **break** is included. Here, we're going to say `for bird in birds: ... else no goose`.

This loop iterates through the birds list and if the bird is "goose", it's going to print "found a goose" and end the loop. Otherwise, it's going to print "no goose". When running this, there's a goose, so we print "found a goose". If we run this again without a goose, we print "no goose".

"WEBVTTKind: captionsLanguage: enhello everyone this is justin from datacamp and today we'll be covering python loops we're going to go over while loops for loops and advanced techniques such as breaking and continuing a loop we're going to be using data camp workspace which is an online id where you can write code analyze data collaboratively and share your insights if you'd like to follow along in this exact workspace you can follow the link in the description below and register for a free account now the first type of loop we're going to cover today is a while loop which will repeatedly run a block of code as long as a condition is true it follows the structure of while and the condition followed by a colon and then the code to run on an indented line below we have a simple example set up here which initializes x to be zero and while x is less than five it will add one to x and then print the value to run this i'm going to click inside the cell i can click run or use a hotkey i'm going to use shift return to run the cell and it is run five times each time adding one to x and when x reaches five it is no longer meeting the condition of being less than 5 and the loop terminates now we can customize how this behaves by adding if and else statements to the loop so let's again write our condition if x is less than 5 but this time let's make x negative five and if x is greater than or equal to zero we will again say x is equal to x plus one otherwise if it's negative x equals x plus 2. in each iteration we still want to print the value of x if we run this we see that the first few iterations x is less than zero so it is added two and then on the final iterations where it is greater than or equal to zero it is added one the next type of loop we're going to cover today is a for loop and a for loop behaves in much the same way as a while loop except it iterates over an editable object such as a list or dictionary it takes the structure of for variable in iterable and then the code to run and in this structure variable is the name you assign to each item that you're iterating through such as each element in a list so let's write a basic for loop here um we already have a list defined of words and we're going to say for word in words print word so word is the variable name we're assigning to each element in this list and we're going to print it and indeed when running this we iterate through each element of the list and print it out another technique you may want to use is to print or to run a loop a certain number of times and to do so you can use the range function so here we're going to write for i in range and then we pass in the number of times we want this to run so we want it to run five times and we're going to print this is run and then we're also going to print out the value of i indeed this runs five times and as you may notice it starts at zero because python is zero indexed as mentioned earlier you can iterate over different types of python objects not just lists here we're going to iterate over each key value pair in a dictionary using the items method so to do so we write for key value in and in the name of the dictionary in this case countries and then we call the items method and then we'll print the key and the value we run this we've iterated through each pair in the dictionary and printed out the key and the value now you can also use the keys and values methods to print out the key in values individually so you're not just returning both another python object you may want to iterate through is a panda's data frame which is a two-dimensional data structure it behaves in much the same way as the items method we just went over so here we have a data frame with uh country and population information um and what we're going to do is we're going to say for the index and row in the data frame um and then we're going to call the iteros method so this will return the index and the row data is a pandas series for each iteration and then we're going to print the index and the row we're going to access one column and we're going to access the country column and if we run through this we've retrieved for each row the index and the data in the country column now sometimes you may want to control a loop um using advanced techniques and one such technique is to use break and continue so here we have a list of duck duckduck.goose duck duck what we're going to do is we're going to iterate through each bird in this bird's list and if the bird equals goose we are going to use the break statement to terminate the loop and then we're going to print a bird and what we'll do is if we run this it iterates through each bird and as soon as it hits goose it ends the loop entirely alternatively if you just want and end the current iteration we can um use the continue statement so let's copy and paste our code from above but this time if it's if the entry is goose we're going to continue and if we run this what we find is that it runs through and when it hits goose it ends the iteration and does not print the bird which would be goose and continues on so it continues to print every other element in the list now the final thing we're going to cover today is adding an else statement after a loop which will run a selected block of code after every iteration is still complete it is still run within the loop so will not execute if a break is included so here we're going to say else no goose so what we're going to say here is this loop iterates through the birds list and if the bird is goose it's going to print found a goose and end the loop otherwise it's going to print no goose so if we run it now there's a goose and it'll say found a goose but if we take this out and run it we'll then finish the iterations there's no break to end the loop and um it'll return no goose so i hope you found this helpful today if you did be sure to like and subscribe and check out the other content included in the description below youhello everyone this is justin from datacamp and today we'll be covering python loops we're going to go over while loops for loops and advanced techniques such as breaking and continuing a loop we're going to be using data camp workspace which is an online id where you can write code analyze data collaboratively and share your insights if you'd like to follow along in this exact workspace you can follow the link in the description below and register for a free account now the first type of loop we're going to cover today is a while loop which will repeatedly run a block of code as long as a condition is true it follows the structure of while and the condition followed by a colon and then the code to run on an indented line below we have a simple example set up here which initializes x to be zero and while x is less than five it will add one to x and then print the value to run this i'm going to click inside the cell i can click run or use a hotkey i'm going to use shift return to run the cell and it is run five times each time adding one to x and when x reaches five it is no longer meeting the condition of being less than 5 and the loop terminates now we can customize how this behaves by adding if and else statements to the loop so let's again write our condition if x is less than 5 but this time let's make x negative five and if x is greater than or equal to zero we will again say x is equal to x plus one otherwise if it's negative x equals x plus 2. in each iteration we still want to print the value of x if we run this we see that the first few iterations x is less than zero so it is added two and then on the final iterations where it is greater than or equal to zero it is added one the next type of loop we're going to cover today is a for loop and a for loop behaves in much the same way as a while loop except it iterates over an editable object such as a list or dictionary it takes the structure of for variable in iterable and then the code to run and in this structure variable is the name you assign to each item that you're iterating through such as each element in a list so let's write a basic for loop here um we already have a list defined of words and we're going to say for word in words print word so word is the variable name we're assigning to each element in this list and we're going to print it and indeed when running this we iterate through each element of the list and print it out another technique you may want to use is to print or to run a loop a certain number of times and to do so you can use the range function so here we're going to write for i in range and then we pass in the number of times we want this to run so we want it to run five times and we're going to print this is run and then we're also going to print out the value of i indeed this runs five times and as you may notice it starts at zero because python is zero indexed as mentioned earlier you can iterate over different types of python objects not just lists here we're going to iterate over each key value pair in a dictionary using the items method so to do so we write for key value in and in the name of the dictionary in this case countries and then we call the items method and then we'll print the key and the value we run this we've iterated through each pair in the dictionary and printed out the key and the value now you can also use the keys and values methods to print out the key in values individually so you're not just returning both another python object you may want to iterate through is a panda's data frame which is a two-dimensional data structure it behaves in much the same way as the items method we just went over so here we have a data frame with uh country and population information um and what we're going to do is we're going to say for the index and row in the data frame um and then we're going to call the iteros method so this will return the index and the row data is a pandas series for each iteration and then we're going to print the index and the row we're going to access one column and we're going to access the country column and if we run through this we've retrieved for each row the index and the data in the country column now sometimes you may want to control a loop um using advanced techniques and one such technique is to use break and continue so here we have a list of duck duckduck.goose duck duck what we're going to do is we're going to iterate through each bird in this bird's list and if the bird equals goose we are going to use the break statement to terminate the loop and then we're going to print a bird and what we'll do is if we run this it iterates through each bird and as soon as it hits goose it ends the loop entirely alternatively if you just want and end the current iteration we can um use the continue statement so let's copy and paste our code from above but this time if it's if the entry is goose we're going to continue and if we run this what we find is that it runs through and when it hits goose it ends the iteration and does not print the bird which would be goose and continues on so it continues to print every other element in the list now the final thing we're going to cover today is adding an else statement after a loop which will run a selected block of code after every iteration is still complete it is still run within the loop so will not execute if a break is included so here we're going to say else no goose so what we're going to say here is this loop iterates through the birds list and if the bird is goose it's going to print found a goose and end the loop otherwise it's going to print no goose so if we run it now there's a goose and it'll say found a goose but if we take this out and run it we'll then finish the iterations there's no break to end the loop and um it'll return no goose so i hope you found this helpful today if you did be sure to like and subscribe and check out the other content included in the description below you\n"