Python Loop Control Structure
Python Loop Control Structure plays a major role in any programming language, In this blog, we going to explore for and while loop of python programming language. We will use these loops when we want to execute any Instruction multiple times for example say you want to print “hello world 10 times” then use can use the concept of for loop and while loop below is the example.
for i in range(1:11):
print("hello World")
Python Loop Control Structure
Basically, we can run the loop in two directions 1st positive direction and 2nd is the negative direction.
for i in range(1,11):
print(i , end=" ")
Ans: 1 2 3 4 5 6 7 8 9 10 (Positive Loop)
Key point: range function generates values from 1 to 10 and places these values inside I variable and finally our print statement is printing these values.
for i in range(10,0):
print(i , end=" ")
Ans: 10 9 8 7 6 5 4 3 2 1 (Negative Loop)
Key point: range function generates values from 10 to 1 and places these values inside I variable and finally our print statement is printing these values.
The same Task we can do using a while loop.
Every Loop is having three-part
1-Start
2-End ( Condition)
3-Increment or decrement Value.
start=1
while start<11:
print(start, end=" ")
start=start+1
Ans: 1 2 3 4 5 6 7 8 9 10
key point: The working of the while loop is the same as for the loop. First, initialize start values that is 1 and then loop while checking the condition like 1<11(True) then loop print perform its task that is print the value of start variable and finally it will increment the start variable by 1.
Now start value is 1+1=2 and again check 2<11(True). If True then print the start value that is 2 and finally increment the value by 1.this process continues and our while will print the and as 1 to 10.
start=10
while start > 0:
print(start, end=" ")
start=start-1
Please read carefully this time we change the symbol > greater then and out loop is not going into negative direction. This time our loop is decrementing the start value by 1.
Ans: 10 9 8 7 6 5 4 3 2 1
I think, your basic fundamental is clear now so now let us jump to the nested for loop in python. What is the meaning of Nesting.? so when we want to put a loop inside a loop is called nested for loop and while loop. let me give you a quick Example.
for i in range(1,5):
for j in range(1,11):
print("*", end=" ")
print()
Ans:
**********
**********
**********
**********
Key Point: Now we have 2 loops outer loop (i loop) and the inner loop (j loop). the task of the j loop is to print(10 stars). the task of the i loop is how many times you want to execute the j loop.
i Values: 1 2 3 4 ( It will execute 4 time for 4 rows)
j Values: 1 2 3 4 5 6 7 8 9 10 ( it will execute 10 time and print 10 stars)
Nested While Loop.
i=1
while i <5:
j=1
while j < 11:
print(j, end=" ")
j=j+1
print()
i=i+1
The Working of Nested while loop is the same as above for loop.
Thanks, Hope this will help.