Transcript for:
Essential Python Loops Explained

Hi everyone, welcome to another video by SimplyLearn. Today we are going to learn about Python loops tutorial. Loops are a fundamental concept in any programming language that is really important to write efficient codes. This video will help you understand loops in Python better.

Before we begin, make sure to subscribe to the SimplyLearn channel and hit the bell icon to never miss an update. So here is the agenda for today's video. Today's video, we will start by learning the basics of loops and look at for loops in Python. Then, we will understand about while loops in Python with its syntax and coding examples.

Finally, we will see how to write nested loops in Python with hands-on demonstrations on the Jupyter notebook. So, let's get started. So, what is a for loop in Python?

A for loop in Python is used to iterate over the items or elements present in a sequence. The items present in a sequence can be in the form of a list, tuple, dictionary or even a string. A for loop in Python uses the range function to iterate over a specific number of times.

Now let's have a look at the syntax of for loop. So here on the left you can see the syntax of the for loop. So we have the for keyword followed by the iterator variable.

then we have the in keyword followed by the sequence it can be a list you can use the range function it can be a dictionary or tuple anything and after that you have your colon followed by the statements that you want to execute in the for loop and below you have the rest of the code and here on the right you can see this is the flow chart of a for loop so you have for each item in sequence then we check the condition if you have reached the last item if that is true you exit out of the loop but if it is false you keep on running or executing the statements that are present inside the for loop this will continue until and unless you have reached the last item in your sequence okay now let's head over to our jupyter notebook where we'll see for loop in detail and we'll explore a lot of code examples okay So here I am on my Jupyter notebook. Let's start by writing a simple for loop. Suppose I have a variable say s and it has a value which is a string let's say simply learn. Okay now the way to write a for loop is I'll say for i which is my iterator variable it can be any valid variable name in python in my variable that is s So here s becomes my sequence. I'll say print i.

So what this for loop is going to do is it will iterate over all the characters that are present in my string and print them one by one. Let me run it by hitting shift enter. You see here using this for loop we have iterated over all the letters that were present in my string that is simply learn and we have printed them one by one. Okay, now the print function in Python provides a parameter called end. So by default the value of the parameter is Backslash n that is the new line character Now you can end a print statement with any character or string using this parameter, which is end Let me show you what I meant.

So I'll again have my same string simply learn I'll say for I in my variable or my sequence s I'll say print i comma then I'll use my end parameter equal to and my end parameter will have a value of asterisk now let me run this you can see here this is sort of a pattern that we have printed so between each letter in my string simply learn we have an asterisk okay moving ahead let's see how to use for loop in a list all right i'll declare a list called programming and this list will contain a few programming languages let's say we have java and then the next item we have in the list is python Next we have Ruby and then we'll have HTML. Okay, so I'm going to print all the individual items that are present in my list using the for loop. So I'll use the same syntax. I'll write for.

This time I'll use my iterator variable name as iter, which means iterator. For iterator or iter in my sequence. which is programming i'll say print iter let's run it you see here we have printed all the items in my list one by one java python ruby and html all right now let's see an example how you can find the average of a list of numbers using for loop so i'll give a comment saying find the average of a list of numbers okay so here first of all we'll declare a list of numbers with variable list underscore num equal to it will have a few numbers let's say 20 25 10 50 and 40 let's make it 45 now to find the average of a list of numbers First I'll declare a variable called sum that will have a value of zero. So we have initialized the sum variable to zero. Then I'll start my for loop for i in my sequence that is list underscore num which is this variable.

Give a colon. I'll write sum equal to sum plus i. So here just give a space to make it more readable so i'm adding all the numbers in my list and we are storing the result in the variable sum then we'll say print sum equal to i pass in my variable that is sum then i'll say print average equal to now our average will be my variable sum divided by the length of my list that has all the numbers let's run this you see here so a total sum of all the numbers present inside the list is 150 and the average of all these numbers is 30 so 150 divided by 5 is 30 alright now let's see how you can use a for loop using a tuple so let's declare a variable called num is going to a tuple of numbers and we have 30, 45, 60, 50 and let's say 70 as the numbers inside the tuple. I'll say sum equal to 0. Then we'll have our for loop for i in my sequence that is num.

I'll say sum equal to sum plus i. So here we are just adding the values that are present inside the tuple. I'll say print sum.

So here you can see we have printed all the values present inside the tuple one below the other. Now if I shift my print statement to here, you can see here this is my sum of all the numbers that are present inside the tuple. So make sure you have the current indentation. Now let's see how you can use the range function in python. Okay, so you can use the range function to iterate over a range of values or numbers using a for loop.

The way to do is I'll say for i in my function range, I'll give my first index at 1 and my second index at or my end index at 10. So this will go from 1 till 9 and exclude the 10th index. I'll say print. i you see here for i equal to range 1 to 10 we have printed all the numbers starting from 1 till 9 so the last index that is 10 is exclusive in the range function now in the range function you can also give a third parameter that stands for step so that you can skip a few steps and print the next value let me show you what i mean you say I write for i in range 0 which is my starting index 10 which is my end index and I'll have a step size of 2 give a colon I'll say print display values with a step size of 2 give a comma here and my variable that is i let's print it there you go so we have printed the values with a gap of 2 so it starts from 0 then we are jumping 2 steps and then we are printing 2 then again 2 steps we have 4 6 and 8 see we are skipping one value and printing the next value in my sequence ranging from 0 to 10. all right now let's write a program to print a table of a given number so i'll give a comment as program to print table of a given number alright so I will pass my variable n which is going to be a user input so I am using the int function and inside the int function I will use the input function to take the user input I will give my message as enter the number I will say for i in range from one to till 11 I'll say multiply which is MUL here and asterisk I so basically what I am doing here is I'll take a user input of the number let's say we want to print the table of five so from one till ten will have the product of the numbers let me print it I'll say print n comma within double quotes I'll give my asterisk comma i comma within double quotes I'll say equal to and then we'll have our variable mul let's run this enter the number I'll give 5 and hit enter there you go so here we have the multiplication table of my number 5 so you see 5 into 1 which is 5 5 into 2 is 10 then we have 5 into 7 35 5 into 9 is 45 then our last index which ends at 10 so we have 5 into 10 that is 50 all right This is how you can create a simple multiplication table using for loop in Python We can also use the range function with a sequence of items The len function can be combined with the range function to iterate through a sequence using indexing I will show you an example here Let's say we have a list called list2 And here we have a list of programming languages Let's say C++ you can either use a single quote or a double quote to represent the text values in a list the next programming language i have is java then let's say i have python and we have r okay so i can write for i in range here i can use the length function and i'll say list to give a colon then we'll print hello and I'll say list 2 of i so what it does is my iterator will iterate over the list of programming languages i have here and it will keep on iterating till the length of the list and then i am printing my message as hello and it will take each item from the list using the index number if i run it you can see here it says hello c plus plus hello java hello python and hello r cool now let's see how you can use nested for loops in python i'll say nested for loop as my comment let's see i have a list of company names my first company i have in my list is google let's say Apple PWC and then we have uber so here I'll write for I in companies I'll say print we will display each letter of I will say plus I now I will use my second for loop sing for letter in I will print the letter let's run it and see our result there you go so here we have used two for loops so that becomes a nested for loop you have my outer for loop and then we have our inner for loop so in the outer for loop we are just printing the name of the company so here we say we will display each letter of plus i which stands for my company name google so you can see below we have displayed each letter of google using the inner for loop similarly we have for apple you can see a p p l e we have pwc and then we have uber so this is how you can use multiple for loops in python now let's see how you can use a for loop with else clause so i'll give a comment for loop with else clause so i'll write for i in range zero comma 10 comma I'll give a step size of 3 I'll say print I and after this Python gives you the flexibility to use an else clause after the for loop so I'll write else print the loop has completed execution so this is my message that we are going to print after we have printed all the elements that are present inside this range function let's run it you can see here we have printed the value starting from zero with a step size of three so we have zero three six until nine and then after that we have our else block printed which has the message the loop has completed execution cool Now let me show you two more important feature that you can use while writing a for loop. One is called the break statement, the other one is called the continue statement. So in Python you can break the for loop and end it before it has actually run all the elements in the iterable using the break statement.

So let me show you a simple example. If I write for, just give a space here. i in range let's say from 1 to 10 i'll use an if condition saying if i equal to equal to 6 then break and come out of the loop next we'll print i so here what we are doing essentially is we are iterating over all the values from 1 to 10 and whenever the i value becomes 6 we come out of the loop and print all the values we have iterated so far let me run it and we'll see the result there you go so here our i value started from 1 we printed 1 2 3 4 5 and then our i value reached 6 then we use the break statement to come out of the loop all right now you can also skip the execution of further statements in the during that iteration using the continue statement in python so when a continue statement is executed the for loop continues with the execution of the next element in the iterable it does not complete all the statements in the for loop body so again we'll i'll give a comment say continue okay so i'll write for i in range again from 1 to 10 give a colon I'll say if my i value is equal to equal to 6 then I'll say continue then we'll print i let me run it and we'll see the result okay so if you notice this output so we have printed values from 1 to 5 and when my i value became 6 we skipped printing 6 and we moved on to the next element in the iterable which was 7 then we printed 8 and 9 so this is how you can use the break and continuous statements in python all right now we'll see a program to display the total goals a player has scored so here we are going to iterate over a dictionary so i'll give a comment program to display the total goals Player has code Alright, first of all, I'll declare a variable saying player name and let's say we have the player name as Carmelo alright, I'll declare a Dictionary called goals and within curly braces. I'll have my first player name addition let's say addition has scored 14 goals then we have let's say burnett so burnett is my key here and then we'll have value in terms of goals let's say 3 and then we have our third player let's say carmelo and carmelo has scored let's say 7 goals now i'm going to write my for loop so i'll write for my iterable name here is player in my sequence name is goals so i'll say goals i'm going to check if my player is equal to equal to player name i'll say print the goals scored by the player so i'll pass my dictionary name and within square brackets i'll say player let's use the break statement and then i'll say else will print my message would be no player with that name found let's run and see the result alright so here what we did was initially I declared a variable called player name that had the value Carmelo and since Carmelo was present inside my dictionary named goals you can see here we have Carmelo who had scored seven goals so I iterated over my sequence goals and I checked if my iterator that is player is equal to equal to the player name which is Carmelo since this Carmelo is present inside my dictionary name so we printed the goals that were scored by Carmelo that is 7 now let's say I change this player name to we have let's say Messi now since Messi is not present inside my dictionary goals if I run this it will print no player with that name found the reason being message not present inside my dictionary called goals cool now we'll see two more examples this time we are going to print the cube of numbers using for loop all right so first of all i'll declare a list which will have a list of numbers let's say 2 5 7 4, 8 and let's say 6 then I'll pass in a empty list so I'll declare within empty square brackets I'll say for i in my sequence name that is num I'm going to use my empty list cube and then followed by the append function and inside the append function we'll have our cubes of the number so i'll write i i'll use the double asterisk operator and then i'll say 3 after that we are going to print my list name that is cube let's run it there you go so you can see here first we have the list of the numbers here and then we have printed the cubes of these numbers in a pattern let's see i bring this print statement here and i'll run it again now this is much more readable you have 2 cube is 8 5 cube is 125 7 cube is 343 then 4 cube is 64 8 cube is 512 6 cube is 216. all right now coming to the last example in our demo section of this for loops in python video will write a program to print a pattern i'll say pattern printing all right so we are going to print a right angle triangle for that i am going to take my first variable called n which is going to be a user input to enter the number of rows so using the input function i am passing the message enter the number of rows i'll say for i in range 0 till my user input n give a colon i'll use my inner for loop this is going to be the number of columns so I'll say for J in range 0 comma I plus 1 give a colon and I'll print my star pattern so I am using asterisks and I'll use my end parameter I'll have my double quotations and then we'll say print the pattern so here what I'm doing is I'm taking the number of rows from the user and I'm iterating from zero till n which is my user input and then we are assigning another for loop for the number of rows so that ranges from 0 till i plus 1 then i'm printing my star let's run it and see the output let's say i'll enter the number of rows as 6 if i hit enter you can see here we have our right angle triangle printed here so initially my i value is 0 so here my j value becomes from 0 till 1 so we have just 1 star printed in the next iteration my i value becomes 1 so from 0 to 1 plus 1 that is 2 we have 2 stars printed the next iteration my i value becomes 2 so 2 plus 1 is 3 again so we have three columns here so three stars printed so on and so forth Alright, if getting your learning started is half the battle, what if you could do that for free?

Visit SkillUp by SimplyLearn. Click on the link in the description to know more. So what is a while loop in Python?

A while loop specifies a condition or a block of code that is to be executed until the condition evaluates to false or the loop is explicitly ended with a break statement. Moving on to the next slide. So here you can see the syntax of a while loop.

So a while loop is defined using the while keyword and then you have the expression followed by a colon. After that you have the statements inside the block. The statements are executed until the condition evaluates to false. Now on the right side you can see the flow chart to show all the steps to execute a while loop. So you can see here we have the test expression.

If the test expression evaluates to true then we execute the statements that are present inside the while block but if the condition is false we will exit out of the while loop now before i move on i have a question for you so here is a python quiz question i want you to tell me the output of the below code so this is regarding a list i have declared a list called alpha that has d f and c as its elements then I'm saying alpha plus equal to ka which is again a string since it is within the single quotes then I'm printing the list now you need to tell me what is the right answer you have four options here a b c and d the first option is d comma f comma c comma k combined then we have ka in the beginning of the list followed by dfc the third option or the c option is dfc ka k being individual elements and the last option the d option is k a d f c please go ahead and solve this question and put your answers in the comment section of the video we'll be more than happy to know from you all right now let's go ahead and start with our demo so here i am on my jupyter notebook let me rename my file i'll say while lopin python demo. Okay, so let me start by writing a simple while loop. I'll declare a variable called i equal to 0. Then I'll start with my while loop.

I'll write my while keyword and this will run till my i is less than 10 let's say. I'll give a colon and if I hit enter it will come to the Next line, you can see the indentation here, which is being maintained. I'll say i equal to i plus 1. So I am incrementing my i value. Then I'll say print i and I'll use my end parameter and I'll say end. Within single quotes, I'll say hash and give a space.

Then let me say print again. So here my while loop will run until my i value is less than 10. So we are continuously incrementing the i value and printing the i value. Let me run it. There you go. You can see the result here.

We have printed the i values starting from 1 till 10 and after that we have come out of the loop. And you can see the hash symbol being used here because we used our end parameter as has so by default it is a new line character but we have explicitly defined our end parameter as has followed by a space cool now let's move on to our next example in this video on while loop i'll define a variable called count and i'll assign a value 0 i'll say while my count is less than equal to 5, I'll give a colon, come to the next line and I'll print the condition is true and then I'll say count equal to count plus 1 and then I'll say print end of loop. Let's run and see our result.

you can see here we have printed our message the condition is true five times because our expression is being evaluated five times here in the sixth time our count is no more less than equal to five so we end the loop and here you can see the message end of loop cool now moving ahead you can also use the break statement in a while loop let me show you how to do it i'll say while true so i am declaring my while loop to be true and i'll say please type your name and i'm going to take my name as input from the user so i am specifying the input function I'm going to check if my name is equal to equal to let's say Gilly then I should give a colon here I'll break out of the loop and then we'll print thank you you typed the correct name all right so what i am doing here is i am going to run this loop till the user enters the correct name so i have declared my name as gilly if you enter any other name apart from gilly this while loop will continue to run and execute let's run it okay so here it says please enter your I'll let's say say John if I run it it is again asking me please enter your name let's say this time I'll say Ami you can see here it is again asking for the name so I'll enter my name let's say Hopkins again our entered username doesn't match the name that we have provided in the code let's say this time i'll say gilly if i hit enter you can see we have our message thank you you typed the correct name okay now moving on to the next example we will see how to find the least common multiple of four and seven so i'll give a comment as lcm of four and seven now you would know It is 28 but we are going to find out with the help of a python while loop. So first I'll declare a variable x equal to 0. I'll say while my expression is true. I'm going to increment my x value to 1. I'll say x plus equal to 1. This means x equal to x plus 1. I'm going to use an if statement and say if. not and here we'll pass the condition x percentage 4 or modulo 4 or x percentage 7 then I'll say break finally we'll print our message saying x comma and I'll say is divisible by 4 and 7 say both 4 and 7 okay so what i am doing here is i am taking my expression while true i am incrementing the value of x each time and checking if this is true or not Now at the first instance when my number x is divisible by both 4 and 7, I am coming out of the loop and we are going to print this.

Now let's see what's the answer. There you go. You can see here 28 is divisible by both 4 and 7 and hence the LCM of 4 and 7 is 28. So this is the least number which is divisible by 4 and 7. Alright. now you can also use the continue statement how you use the break statement to come out of the loop you can also use the continue statement to continue running the loop so i'll say i equal to 0 while i is less than 10 so this is my expression my loop is going to run until i is less than 10 i am going to increment the value of i i'll say i plus equal to 1 if let's say i set my condition if i equal to equal to let's say 6 then I'll say continue my execution and skip the current step where i value becomes 6 then I'll say print i let's run it and see the result okay you can see here we have printed 1 2 3 4 5 and here you can see we have skipped the execution where i value became 6 and continued with the next iteration 7 8 9 and 10 you So this is how you can use the continue statement and the break statement in a while loop. All right.

Now moving ahead, you can also use the else statement in a while loop. Now let me show you how to do it. I'll say I equal to 1. Then I'll write while I is less than let's say 5. I'll say print I.

Then I am going to increment the value to i plus equal to 1. Now here you can use the else statement and say print i is not less than 5. Let's run it. You can see here we ran our loop until i value was less than 5. So we printed. 1 2 3 and 4 when i value became 5 we printed i value is not less than 5 cool now moving ahead so you can use inbuilt functions inside a while loop let me show you how to use the pop function and remove the elements in a list using a while loop so i'll declare a list of numbers let's say 1 comma 2 comma 3 4 and we have 5 so these are the 5 elements that are present inside list a i'll say while a so i'm iterating over all the elements in my list i'm going to say print a dot i'll use the pop function so what pop does is it is going to remove the elements from the end of a list then I'll say else print there are no elements left in the list alright let's run it and see the result you can see here we are removing the elements one by one from the end of the list.

So first we popped out five, then four, three, two and one. And after that, we had no more elements left in the list. So we printed there are no elements left in the list. Okay, now the next program, we will take numbers as input from the user and calculate the average as long as the user enters a positive number.

So I'll give a comment. average of positive numbers cool okay so I'll start my program I'll declare a variable called num which has a value 0 I'll declare a variable called count which also has a value 0 then I have sum which has a value of 0 I'll write while you my number is greater than equal to zero so this condition is for accepting only positive numbers i'll say num equal to i'm going to take the positive numbers from the user so i'll pass an input function i'll say enter any positive number Then I'm going to say if my number is greater than 0 I'll say count equal to count plus 1. Let's make this greater than equal to 0. Then I'll say sum equal to sum plus my number. So here I am keeping track of the numbers that we have entered and here we are calculating this sum that is the cumulative sum.

then I'll say abg which is to find the average I'll say sum divided by my variable that is count then I'm going to print total I'll say total sum of numbers give a colon followed by a space give a comma i'll say sum then i'll say average give a colon followed by a space and i'll pass in the variable avg all right so here i have my program ready where we are using a while loop and an if statement to take numbers as input from the user and calculate the average as long as the user enters a positive number. So let me run it. Okay, it says enter a positive number. I'll say let's say five.

Again, it's asking for a positive number. I'll say seven, let's say 10. And this time, I'm going to enter a negative number so I'll say minus 6 if I run it you can see here the total sum of numbers 5 plus 7 plus 10 is 22 and the average is 22 divided by 3 which is 7.33 all right let me give a space here for more readability we are going to try it again I'll say 40 50, 30 and let's say 100. This time I'll enter a negative number let's say minus 90. Okay so you can see here I have entered four positive numbers 40, 50, 30 and 100. So the sum of numbers is 220 and the average is 40 plus 50 plus 30 plus 100 which is 220 divided by 4 which is 55. cool now moving on to the last demo in this while loop with python tutorial so here we are going to guess a number so the user is going to give a number between a certain range and based on a random input generated from the program we are going to guess the random number all right so I'm going to start by importing my library called random. I'm going to say n equal to random dot randint which is a function to generate random integers. I want to generate between 1 and 100. Let's go ahead and print that number n. Then I'll use a variable called guess.

which is going to be a user input so i'll say input which is my function and i'll give the message enter an integer between 1 to let's say 100 okay then i'll start my while loop saying while n not equal to my variable that is guess I'll say if my guessed number is less than n I'll print the message as your guess is, let's say, low. then again I will say guess equal to I'll take the user input I just copy this message and we'll print it here okay now I'll say elif if my guess is more than my random integer will print i'll just copy this we are going to print your guesses let's say high then we are again going to ask the user to guess a number between 1 to 100 and after that I'll say else will print you guessed it correctly then we'll break out of the loop and finally I'll just print it okay so what we are doing in this game is before that let me just give a comment as guessing game in python first of all we are generating a random integer using the library called random so the integer will lie between 1 and 100 i am going to print that integer after that i am taking a user input so i am asking the user to enter an integer between 1 to 100 and i am checking if my random integer is not equal to my user input that is guess and if that guess is less than my random integer I am going to print your guess is low then I am again asking the user to input an integer between 1 to 100 then I am saying if the guessed value is more than the generated random integer will print your guess is high then after that I am again asking the user to input an integer and in case the random integer matches with the guest number will print you guessed it correctly all right let's try this out okay so here you can see so my program generated a random integer 48 that lies between 1 and 100 so our loop will only stop executing when we enter our number as 48 otherwise it will keep on running and asking you to enter an integer let's say i enter 50. you see here your guessed value that is 50 is more than the random integer 48 so we have the message your guess is high let's say i'll say 30. this time my guess is low you can see it here let's say i'll take my number as 300 you see here this time my guess is high which is more than 48 but if i say my user input to be 48 and i if i hit enter there you go we have our message printed you guessed it correctly all right Choose from over 300 in-demand skills and get access to 1000 plus hours of video content for free. Visit SkillUp by SimplyLearn.

Click on the link in the description to know more. What is a nested loop? Python programming language allows you to use one loop inside another loop. This is known as a nested loop. It is present inside the body of the outer loop.

The inner or outer loop can be a for loop or a while loop. The outer for loop can contain a while loop. or an outer while loop can contain a for loop inside it.

In Python nested loops, the outer loop can have more than one inner loop. There is no limitation on the chaining of loops. Now you can see on your screens the basic syntax of writing a nested loop in Python. You have the outer loop followed by the inner loop and the statements inside the inner loop. And finally, you have the statements of the outer loop.

The last three lines consist of the body of the outer loop. Now talking about the various ways of writing nested loops in Python. So with Python you can write a for loop inside another for loop or you can have a while loop declared inside another while loop. You can see it here. So using Python you can use both for loops and while loops together.

The outer loop can be a for loop and the inner loop can be a while loop. You can also write nested loops having a while loop outside and for loop inside. So now that you have learned about the basics of nested loops, let's look at an example of printing patterns so in the code here we have used two for loops to get our right angle triangle containing asterisks or stars so we have declared row equal to 7 which means we need 7 rows to be printed you can count it here these are 7 rows hence we have defined it as row equal to 7 now the outer for loop ensures we have a total of 7 rows so we have defined a range from 1 to row plus 1 that is 8 now the inner loop is the total number of columns in each row so for each iteration of the outer loop the columns count gets incremented by 1 so for the first iteration of the outer loop the column count is 1 in the next iteration it is 2 and so on the inner loop iteration is equal to the count of the columns and for each iteration in an inner loop we print a star so for the first iteration when i value is 0 it will first print a blank when i value becomes 1 then your j range becomes 1 comma 1 plus 1 which is 2 so it will print 1 star here followed by a space when i value becomes 2 your j range becomes 1 comma 3 so it will print 2 stars then again when i value becomes 3 your range becomes 1 comma 4 so it will print three stars so so on and so forth now let's see when you should use a nested loop in python so nested loops are mostly used to work with multi-dimensional data structure such as printing two-dimensional arrays iterating a list that contains a nested list etc you can use python nested loops to print different star or number patterns as well now let's head to our Jupyter notebook to do some practical hands-on demonstrations to understand nested loops in python better okay you can see here i am on my Jupyter notebook first of all i'll rename my notebook as nested loops in python demo click on rename all right now let's see our first example so here we are going to print the items in a list one by one but each letter in an item should be separated by the at sign which is basically the at the rate symbol that you use in your email ids all right and for the first demo we'll be using nested for loop so let's start i'll create a list which will have the names of the fruits let's say we have mango, I'll give a comma, let's say I have apple, grapes and let's say we have banana, alright, now I'll create my outer loop, so I'll say for fruit, now this variable can be any, valid python variable this is basically known as an iterator on an iterator variable so i'll say for fruit in my list which is list underscore fruits that i have declared in my first line i'll give a colon and then declare my inner loop i'll say for i in my variable or the iterator that I had declared in the previous line which is fruit I'll say print i and then I'll use the end parameter that will have the at sign and then I'll print a blank so this is my first nested loop that I have created so I want to iterate through all the items present in my list underscore fruits variable and for each item in the list I want to make sure that each letter in an item should be separated with the at sign so let me go ahead and print it so that you can see the result there you go so here you can see we have printed the different items that were present in my list which was list underscore fruits and for each item the letters in the item have been separated by the at sign you can see here Alright, if you want you can change this symbol to let's say star.

If I print it, you can see the difference in the result. Now we'll see our second example where we are going to print the values of items in two lists together. So let me create a list called color that will have the different colors such as red you have green and let's say blue and the next list i'm going to create will have three items the first item is apple then we have veggies and then we have shirt now now To print the values of the items in these two lists together, I'm going to use two for loops again. So I'll say for my iterator variable, let's say x in my first list, which is color. So I have declared my outer loop.

And now I'll say for another iterator variable, let's say y in my second list items, I'm going to print. x comma y and after that we'll print a space so first of all my outer for loop will iterate through the items that are present inside color list and for each color we are going to iterate through the values that are present inside items list you now let me go ahead and print it you can see it here first we are printing red apple red veggies and red shirt then we have green apple green veggies and green shirt if i scroll down you can see blue apple blue veggies and blue shirt okay now coming to our third example here we are going to print a right angle triangle with 10 rows we have seen a similar example in the slides where there were seven rows now we are going to print a right angle triangle with 10 rows i'll give a comment let's say print right triangle okay so i'll start my for loop i'll say for any iterator variable let's say i in range I'll pass my range as 11 so it will go from 0 to 10 then I'll say for j in range i so this will take the number of columns I'll say print within double quotes I'll give my star because I want to print a star pattern for the triangle and I'll end with a space then I'll say print blank so there won't be any space between the different rows now let's print the result there you go so here you can see we have a right angle triangle of 10 rows you can count the number of rows and also we have the number of columns as 10 so when i value is 1 your g range also becomes 1 so we print 1 star then when i value is 2 we are going to print 2 stars when i value is 3 we are going to print 3 stars and we are using the end parameter as a space okay now let's go ahead and print a right angle triangle using a nested while loop so unlike the for loop the while loop doesn't have a precompiled iterable sequence The while loop keeps executing the code until the expression evaluates to true. So I'll start with the variable i equal to 11 because I want to print 10 rows that will contain my star pattern.

Now I'll declare my first while loop. I'll say while i is greater than 0. So my loop will continue. until i is greater than 0 i'll say j equal to 11 then i'll use my inner while loop i'll say while j is greater than i will print star and i'll use my end parameter as space again Then we are going to decrement j by 1. I will come out of the inner while loop and I will say i equal to i minus 1. So we are also decrementing the first variable i by 1 and now I will say print.

Okay, so let me run this. You can see it here. We have the same pattern printed.

earlier we saw this using two for loops and now we have created the same pattern using two while loops all right now moving to our next example where we'll see how to append two lists so first of all i am going to declare list one and list two and we are going to append the elements of both the list into an empty list called result so I'll give a comment append to lists okay so first I'll declare my list one now these are list of numbers let's say I have 10 25 and 30 as my elements in the first list and then I'll declare my second list which will have let's say 60 15 and 50 okay Now I'll declare an empty list called result and after that I'm going to start my outer for loop. I'll say for i in my list 1 then I'll say for j in list 2 I'll say result which is my empty list that i have declared then i'm going to use the append function that is inbuilt in python i'll say i plus j so this will make sure we'll append the values from both the list into my empty list which is result then i'll say print result okay let's run it there you go so what we are doing here is i am adding each element in list 1 with all the elements in list 2 if you see here 10 plus 60 is 70 then we have 10 plus 15 which is 25 10 plus 50 is 60 similarly 25 plus 60 is 85 25 plus 15 is 40 then 25 plus 50 is 75 and similarly for 30 plus 60 30 plus 15 and 30 plus 50. great Now moving to our next example, we are going to see how you can multiply the values in two lists. So I'll give a comment saying multiplying two lists.

I'll declare my first list which is list 1 with 2, 4 and let's say 6. Then I'll have my list2 with the same elements 2, 4 and 6. Start my outer for loop for i in list1. Then I'll say for j in list2. I'm going to show you another feature that you can use while implementing nested list. that is to use continue or break so i'll say if i equal to equal to z then I'll continue after that we are going to print the value of i followed by the asterisk then the value of j will give a comma then within single quotes I'll say equal to then I'll give the operation i multiplied by j so this is how you can multiply the elements in two lists so I've declared my list one my list two then I'm using two for loops and whenever my i value is equal to equal to j we'll skip that step and move on to the next iteration let me run it and show you the result so if you notice here I haven't multiplied 2 and 2. The reason being I have used this if condition.

Whenever i was equal to j, we continued with the next iteration. Similarly, there is no output for 4 multiplied by 4 or 6 multiplied by 6. But for the remaining, we have our result. 2 multiplied by 4 is 8. 2 multiplied by 6 is 12. Similarly, 4 multiplied by 2 is 8. 4 multiplied by 6 is 24 6 multiplied by 2 is 12 and 6 multiplied by 4 is 24 so continue and break our two statements that you can use inside nested loops in python okay now we are going to write another nested loop using a while loop and a for loop to check whether a number is a perfect number or not so basically in this program we are going to print the perfect numbers between 1 and 100 now a perfect number is a positive integer that is equal to the sum of its proper divisors so the smallest perfect number is 6 which is the sum of 1 2 and 3 so these are the perfect divisors of or proper divisors of 6 1 2 and 3 if you add them the value is 6 another example is 28 the proper divisors of 28 are 1 then you have 2 4 7 and 14 if you add them the value is 28 so here we will iterate the first 100 numbers using a while loop so for each iteration of the outer while loop the inner for loop executes from 1 up to the current outer number to check if the current number is a perfect number or not okay so i'll give a comment saying perfect number cool so if I'll first declare a variable called a which will have a value of 1 then I'll say while my a is less than equal to 100 then I'll declare another variable called y underscore sum which will have the value of 0 after that I'll pass in my inner loop which is the for loop I'll say for i in range 1 comma a I'll say if a mod i is equal to equal to 0 then we'll say y underscore sum equal to y underscore sum plus i Then I'm going to say if my y underscore sum value is equal to equal to my a value then it's a perfect number. So I'm going to use a print statement saying print perfect number give a colon then I'll give a comma and print my variable a. Finally, we are going to increment the value of a to 1. Now let's run it.

You can see it here. Between 1 and 100, we have two perfect numbers. As I mentioned earlier, 6 and 28. Okay.

Now coming to the final example in our demo on nested loops in Python. Here we are going to print each element in the list five times. so I'll first declare my list let's say fruits which has apple then we have orange and let's say we have kiwi so I'll say for an iterator fruit in fruits I'll declare a variable called count and initialize it to 0 then I'm going to use a while loop saying while count is less than 6 since I want to print the items in the list five times then I'll say print fruit and I'll use my end parameter as a space then we are going to increment count by 1 and finally I'll print it.

Let's run it. You can see it here. I've printed each element in my list fruits five times. You can see it here. Alright, thank you all for watching this video on Python loops tutorial.

I hope you enjoyed it. If you have any queries, please feel free to put them in the comment section of the video. We'll be happy to answer them. Thanks for watching. Stay safe and keep learning.

Hi there, if you like this video, subscribe to the Simply Learn YouTube channel and click here to watch similar videos. To nerd up and get certified, click here.