-----
Install Python:
- MacOS: https://www.jcchouinard.com/install-python-on-macos/
- Windows: https://www.jcchouinard.com/install-python-on-windows/
- Anaconda: https://www.jcchouinard.com/install-python-with-anaconda-on-windows/
Subscribe to my Python Course waitlist: https://ba995fe7.sibforms.com/serve/MUIEAPv50TFkNuoknCNvzRUKLLhvvZd5jzCwEZvi9BNjtkhVuEtLpEG58-Khdquyg9v5V-1qeGDwIXy739I4eFIVcCqeqqV3UUisW_-hAd5ljC1dGMrQvXHC7JvORh9TbnLA1CHqWro4N7YVZ4730-D5dXGxqd3CbaVHSJpS5fyylPMVzCe1_y9xOTl2-CsvEuhO01E0Ytv59HEJ
Support my work: https://www.buymeacoffee.com/jcchouinard
Subscribe to this channel:
https://www.youtube.com/channel/UCthJJqyUGdI5EA0YjnjXthw?sub_confirmation=1
Follow me: https://twitter.com/ChouinardJC
https://www.linkedin.com/in/jeanchristophechouinard/
https://www.buymeacoffee.com/jcchouinard
https://www.youtube.com/channel/UCthJJqyUGdI5EA0YjnjXthw?sub_confirmation=1
Show More Show Less View Video Transcript
0:00
Hi everyone, my name is Jean-Christophe Chouinard. In this beginner Python tutorial
0:04
we will learn about Python loops. There are two types of loops in Python, the for loop and the
0:10
while loop. Those loops are control flow statements that you can use to repeat a block of code again
0:19
and again and again and again. The while loop will loop recursively as long as the condition is true
0:26
so it can loop infinitely. The for loop allows you to give you a sequence on which to iterate over
0:34
So let's look at the first type of loop. So the while loop executes until the condition
0:39
becomes false. So it will loop forever as long as the condition is true. So we could say i equal 10
0:46
or i equal 0 and we could say while i is less than 5, print i and at each iteration we could
0:55
say i plus equal one so we would add one to the to to i element so we can see that it looped
1:02
until the condition was met and then stopped one thing to be aware of is that a while loop
1:10
runs as long as the condition is true so if you say while true and you said print hello for example
1:16
and then you run this it will run forever as long as the code is not stopped so here i'm
1:22
interrupting it but it would have printed for as long as the condition is true and in this case that
1:29
was forever. So in order to prevent that we could say use the break statement so we could say while
1:35
true print hello and in this case if we use the break statement it will loop only once because
1:43
we decided to break it after the first iteration so it printed it only once. One last concept I
1:51
want to introduce with the while loop is the else statement. So the while loop operates a bit like
1:56
the if else statement and you can also do it. So let's take our previous loop that we have seen
2:04
and what we want to know is whenever it breaks we want to print a statement that says i is greater
2:13
than five. So if we do this we can then return something. So it did the entire loop and when it
2:20
break broke it returned the print statement. Next we have the for loop so in this case the for loop
2:28
is iterating through a sequence so while the while loop was always running as long as the condition
2:34
is true the for loop can allow you to give gates on which it should loops on so for example we
2:42
could say for i in and we could a sequence which is a list this case and we can say print i
2:50
Running this, we can see that it went through each element of the sequence and it printed it
2:57
You can loop other types, for example you can loop a string
3:02
So we could say for letter in hello, then we could say print letter
3:08
So you don't have to loop through a list, you can loop through any type of sequence in Python
3:15
Again we can use the break statement in the for loop so for example if we take again this loop
3:23
that we had we could say if letter equals equals e then we could say break the loop so as print each
3:38
element when the letter equals it then you break it. So the break statement stopped the loop early
3:45
and we ended up with the statement. So we have just seen how the break statement
3:54
stopped the loop early. The continue is also another control flow statement that can be used
4:00
in order to skip to the next situation in the loop. So for example what we could say is we could say
4:06
for letter in python and we can say okay if the letter equals equal h then we could say continue
4:22
So in this case the loop doesn't stop we say print letter it doesn't break it just
4:28
skip to the next iteration so when we look here it printed each letter apart from the h
4:36
So we already saw that the for loop just iterate through a sequence of elements. So in this case
4:43
the range function is returned the sequence of elements. So you could say for i in range
4:53
5 and we could say print i. So then what we will do is you will print each element from
5:00
0 to 5 using the range function. You can also use the range parameters in order to increment. So you
5:10
could say for x in range and then we could say print x. So here what will happen is you we will
5:20
start with the 2 and then we will end at 20 and we will increment by 2. So if we use that for loop
5:28
we see that okay two four six eight ten blah blah blah until we reach 20 So we can also nest loop within loop so you can also create a loop inside of another loop and the only way the simple way to do this is you do the for i in and you could say abc and then by
5:48
convention what you'll do is you'll move to the next letter so if you're inside it you would say
5:54
for j in def and then you could print i j so what will happen here is it will loop through each a's
6:06
and then for each a will loop through the def and then it will move to the b's def and the c's def
6:15
so this looping nested looping technique is very useful in python to do things such as looping
6:22
through a nested list. So if you want to print each of these elements, for example, you could use the
6:27
nested for loop by saying for i in or for nesting in list and then you could say for i in nest
6:39
and then you could print i. So what will happen here is you'll print each of the nested element
6:46
because without that you would have just did a simple loop and have done for listen nest and
6:53
you would have printed the entire list. If you want to loop through dictionaries now there are
6:59
many ways you can do it but you can use the dictionaries method to do so. So if we have that
7:06
dictionary if we print that my dict if we return that to the the console we see that we have a
7:12
dictionary and we can use the myDictKeys method in order to just get the keys. So we can see that
7:21
this method will return a list of the keys from the dictionaries or you could use the myDict
7:29
values. Let's just look at the the methods for now but this method would return the values
7:36
instead of the keys or alternatively you can use the items method to return the output as a tuple
7:48
So in this case you're creating a list of tuples for which we can loop. So if you look at this
7:55
pattern you'll see that it's similar to looping through nested items. So let's look at how we can
8:02
print keys for example. Using the for loop we can print all the keys of the dictionaries by
8:09
looking at for x in my dict and keys. We've seen that the keys method return all the keys from the
8:17
dictionary so then if we print x we'll see that we're printing each key. We can also print the
8:24
values from it using the keys method so you could say okay my dict x because in this case what we're
8:33
doing is we're selecting the key from the dictionary so here we're printing the values from the
8:42
dictionaries. So far I hope this is not too confusing if you've never done essentially what
8:51
this is is if I'm taking my dictionary and I'm selecting name from it I'll have the value right
8:59
so in this case it's exactly what it does but it's just looping through each value. The alternative
9:05
way to do this is to use them the values method on the dictionary so you could say for x in my dict
9:14
values then instead of having to select it we're just printing x this time and we're again returning
9:24
all the values so if you want to print keys of values then it would be very complex to say okay
9:29
for key in my dict keys and then you would say okay for
9:44
So print key, and then you would say myDictKey. So then you would, in this way, what you'll do is you would print the key values, right
9:58
A better way to do this would be to use the items method just as what we've seen
10:03
And what we would do is instead of saying for key here, we would say for key value
10:08
and then it would iterate through each of them. similarly but in a much simpler way. In Python there is a concept of iterators. An iterator
10:23
in Python is an object that it can be iterated upon. So by definition we can use a for loop to
10:29
iterate through an iterator. So one of the examples of this is an enumerate function
10:36
returns an object that can be iterated upon. So if we just return the object here what we'll return
10:43
is an object for which we can loop and if we want to get the first element we could use the next
10:49
function for example to go this. A better way to loop through that iterator however is to use the
10:57
for loop. So for example we could say we can use the enemy rate list here and we could say for index
11:06
letter in n rate list equals print f index and return the index here and say letter
11:23
This is a good way to just show what is the index of your element
11:31
Otherwise what you would have needed to do would have been to say okay for so we could have
11:37
instantiate i equals 0 for letter in list print i letter and then we would have done i plus equal
11:50
1. So that would have been a second way to do the same thing as what we just did so the
11:56
intramarator is very useful for you to do this kind of logic. Next we will loop through pandas
12:05
data frame. So if you've never seen what a pandas data frame is, it's essentially what's built on
12:11
NumPy and it creates and uses arrays to create table like structure. So for example if I run this
12:19
pandas data frame here what I have is a pandas with the column I gave it, the index I gave it
12:26
and the values associated with each element. So if we want to loop through each element in the
12:34
pandas data frame for example what we'll need is to use a for loop again so we can say for column
12:42
in data frame and then we can print the column so that's how you loop through each of the column to
12:49
print them off otherwise you can use the iterose method so if you do df iterose
12:56
you will end up with a generator object and from that generator object you can use the
13:06
next method and say okay let's run this it and we return the area object and then what we'll do
13:21
is we'll get the first row with each of the column using the df iter row. We can start
13:31
integrating this with the for loop so we can say for index row in df iter rows and what we could
13:40
do is say okay let's print the index first and run this. So what we'll see is we're printing each
13:49
of the index here. We can also print each row. So we can take this iterator object and we can start
14:00
splitting it into each of the elements and then we can decide to print the type of the row. For
14:07
example, if we run this again, so what we'll see is that we are running the index here, we're running
14:18
the row so we're printing each column and for example for each of the column we could say okay
14:25
just like one element so column one here double quotes like this
14:41
and here you can say that I wrote So we can see here I selected the element from column 1 here this way
14:55
So there are many ways so you can select each index from the data frame
15:03
You can select an entire row. You can select one element from a row using the row and column
15:09
And you can also show for example the type which is Cpandas series here
15:16
So let's do that again just for simple more clarity. So we can say for index, row in df, either rows
15:28
And then we can say print the index. And I just want to loop through one of the columns this time
15:37
And I just want to print the row for the column one
15:41
and then we print this and we can see that it looped through each of the element but just for
15:47
one column this time. Cool, so now we have learned while loop, for loops, we've learned how to use
15:54
generator objects to loop, we've learned how to loop to pandas data frame. Let's dive into slightly
16:01
more complex concepts and one of these is how do you break multiple loops because if I take this
16:10
loop here. I will range through the value from 0 to 9 and then I will range a loop from each a, b
16:19
and c and then I will print ig. What I want to do here is I want to break the entire loop as long as
16:25
soon as I reach the letter b. So I just use the if j equal b then break. If I run this I would have
16:34
assumed that it would have broke the entire thing, right? But what it did is it looped to the I value, AB, and then broke the second loop
16:45
So we never printed C That not what I wanted I want the entire loop to break If you want to do this we don break using the break statement What we would do instead is we would use a function to say for define breakout
17:03
and we can put this entire thing inside the function and instead of using the break statement
17:11
I would have used the return statement. I won't dive too much into what this is, but using the
17:18
the return statement will immediately exist the function. So it will stop the function as soon as
17:26
you return the statement. So in this case if you want a loop multiple loops, break multiple loops
17:32
you just enclose it into a function and if you run this then you have the correct behavior where
17:39
the entire loop broke when you reached the letter B. Finally, I want to teach you one thing is that
17:48
for loops can become very very big because you start using for loop and then you end up with
17:54
stuff like for i in and then for j in and then for l in and then for blah blah blah. This can
18:06
become very complex to read in code. So it is good to know how you can avoid
18:13
for loops when you can. There are three ways that you can, three main ways that
18:18
you can avoid for loops is one you can use list comprehension, the other you can
18:24
use some functions plus the lambda function. So for example if I have this
18:32
for loop it will print each value it will print a list where it had appended the values in range 10
18:42
If you want to convert this into a list comprehension instead what you would do here
18:49
is you would say okay you use the square brackets i4i in range 10. And in this case you can print
19:02
ls2 and just say print ls2 and this list comprehension does the same thing as what this loop does
19:17
The second technique that you can use to avoid a for loop is to use the map function along with
19:24
the lambda. So if I'm taking that list what I'm doing here is I'm taking a list from range 10 but
19:31
I'm doubling each element and append it to a list so I end up with 0, 2, 4, 6, 8 with even numbers
19:42
Instead of doing this you could have said okay list2 equal and you use the map method and in the
19:49
map method you first need to provide a function and then what is the iterator you use on. So in
19:55
this case you use range 10 similar to what we've done it here and here in the function we replace
20:07
this by lambda x x times 2 and if you print that second list again you will see that you end up
20:19
with a map object so instead of printing this what you want to do is return the list element
20:27
of all that and you can see that we have the same result without using a for loop this time
20:38
the last way to avoid for loops that I want to introduce is getting using the filter method
20:45
again with the lambda function so here what i have is a list and i will just want
20:53
append the even numbers so here i have in range 10 and i use the mod
21:01
modulus operator and one when the modulus is equal zero then i append i
21:08
and the result is the fact that i'm just appending even number here
21:12
If I want to do the same thing without a for loop this time I would use the filter method
21:19
the filter function, sorry. And the filter function works similarly to the map function
21:26
What you want to prove give is one function here and you want to put a your iterator here on second
21:36
argument and what we'll do is we'll replace the function by lambda x x
21:48
modulus 2 equals equal 0. So essentially we're doing the same thing as what we were doing with
21:55
the if and we're do applying the filter and if we print even 2 then we will show again an object
22:05
instead so we have to put it as a list instead and doing this we end up with the same result
22:15
Thank you very much, help me unsubscribe to this channel and stay tuned for my upcoming
22:20
Python for SEO course which I will link in the description below. You can follow
22:25
me on any of these platforms. Thank you very much, see you next time
#Computers & Electronics
#Programming

