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

Justin covers while and for loops in Python, showing how to iterate over lists, ranges, dictionaries, and DataFrames. He demonstrates break and continue statements to control loop flow, then explains the loop-else construct, which executes only if the loop finishes without hitting a break.
Chapters
Hello, 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 datacamp 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 then 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 0. And while x is less than 5, it will add 1 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 five 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 minus 5, and if x is greater than or equal to 0, we will again say x is equal to x plus 1. Otherwise, if it's negative, x equals x plus 2, and 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 0, it is added 1. 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 iterable 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 we already have a list defined of words, and we're going to say for wording, 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 then 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. If 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 and values individually. So you're not just returning both. Another Python object you may want to iterate through is a pandas 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 country and population information. And what we're going to do is we're going to say for the index and row in the data frame, and then we're going to call the iterrows method. So this will return the index and the row data as a panda 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 using advanced techniques, and one such technique is to use break and continue. So here we have a list of duck, duck, duck, duck, goose, duck, duck. What we're going to do is we're going to iterate through each bird in this birds list, and if the bird equals goose, we are going to use the break statement to terminate the loop. Then we're going to print the bird. 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 to end the current iteration, we can use the continue statement. So let's copy and paste our code from above. But this time 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 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. SA.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







