python Loop and Iteration

In this article, we are learning about python loop from basic to advance. Loop is also calling iteration. The loop is using when the same code run in multiple time. There are two types of loop in practices. One is for loop and another is while loop. Here we are learning about this loop. For loop is applicable when you want to repeat your code for some iteration. But in case of while loop scenario is different. You can run loop until a certain condition is met. Now let’s understand about loop by their syntax and code.

Python for loop

The definite loop also calls for a loop. It’s definite because the loop is executing the exact number of time. For loop have an explicit variable that changes each time through the loop. The loop starts with for keyword after that iteration variable is place. The accessibility of this variable is within a loop. The sequence is at the end. End of the statement is indicating by clone(:). Here is a simple example of for loop.

python for loop
python for loop
for i in [4,5,6,7,8]:
    print(i)

Above code show the simple example of for loop. Some operation is performed on loop for different propose here are some example of them.

Find Largest Value Through Loop

Here we make a program that finds the largest number in a list using for loop. We make variable largest_number that contain the largest number. In this program in every loop, the current value is comparing with the previous value. After that is current value is greater than the previous place largest value with current value otherwise compares with the next one. Here is the code for this problem.

largest_number=-1
for i in [100,60,90,150,120]:
    if i>largest_number:
        largest_number=i
print(largest_number)

Counting in Loop

To count how many time for loop execute. The count variable is introducing for this problem with initial value 0. Every iteration count value is increment by 1. Here is the code for this problem.

count=0
for i in [100,60,90,150,120]:
    count +=1
print('Total element is ',count)

Summing on loop

To the sum of the total element in a list by using a loop. A total_sum variable is introducing for this problem with initial value 0. Every iteration value is the sum with previous. A final iteration, we get a sum of the element. Here is the code for this problem.

total_sum=0
for i in [100,60,90,150,120]:
    total_sum=total_sum+i
print('Total sum is ',total_sum)

Finding Average Value in Loop

To find the average value by using a loop. SO two total_sum and count variable is introducing for this problem with initializing value 0. Every iteration value is the sum with the previous value and assigns to total_sum variable. Likewise, every iteration count value is increase by one. After that at the end of the iteration average of the element is calculated. Here is the code for this problem.

total_sum=0
count=0
for i in [100,60,90,150,120]:
    total_sum=total_sum+i
    count +=1
average=total_sum/count

print('Average is ',average)

Filter in Loop

If statement is used to filter the element in the loop and catch element that satisfies the condition. Here is a program for a filter in a loop.

for i in [100,60,90,150,120]:
    if i>100:
        print('Larger than 100 is ',i)

Python While Loop

while loop is also known as an indefinite loop because it’s iterate until the logical operation is false. It’s very easy to define the loop is terminate or not. While keyword is used for this loop. We can easily define while loop. Generally, while keyword follows by condition and clone. Here is a flow chart of while loop.

Python While loop
n=5
while n>0:
    print('hello')
    n=n-1

There are some term are use in while loop some are explain here.

python Infinite Loop

Those loops which are not terminate is called an infinite loop. The code is in an infinite loop because the conditional statement never becomes True. If our program is going to infinite loop by mistake then need to terminate kernel for stop execution. Here is a simple example of an infinite loop.

n=5
while n>0:
    print('hello')

In the above code, the conditional statement is always true because every time the value of n is 5. So if you want to make program terminate than the value of n should decrease at every iteration. After that, the conditional statement is false then exit from the loop.

Break & Continue

break statement ends the current loop and jumps to the next statement after the break statement. Continue to break the current loop and back to the top of the loop next iteration starts from the top. Here is an example of break and continue statement.

for i in [4,5,6,7,8]:
    if i==6:
        break
    print(i)
print('Loop end')
for i in [4,5,6,7,8]:
    if i==6:
        continue
    print(i)
print('Loop end')

Range Function

Some built-in function is applying in the loop. Most use one is range function. The range function is using for creat an iteration data. Generally, it takes start point endpoint and step. Range function return iteration number.

for i in range(1,10):
    print(i)

Project

Do project nowhere implements all the concept we learn and doing a small project. Overview of our project is generating like this. Firstly generate a random number between 0 to 100. and the user allows predicting the number. If the user successfully predicts that number then the program is terminated. After the random number is generated take number from a user by input function. And convert that into an integer. After this, all the code are put into try block for allowing the user only input number. Some condition is applying for the guide input value. If the user successfully predicts that number then show congratulations message and program is terminated. Our program syntax looks like this.

  1. Generate a random number.
  2. Initialize guess=0
  3. while random!=guess
    1. Take input from a user
      1. if a guess is greater than 100 show this message
        Enter a number between 0 to 100
      2. if a guess is greater than random show this message
        Your number is large
      3. if a guess is less than random show this message
        Your number is small
      4. if a guess is equal to random show this message
        Congratulations you won
      5. Terminate program
  4. End
import random
random=random.randint(1,100)
guess=0
print(random)
while random!=guess:
    try:
        guess=input('Enter a number between 0 to 100: ')
        guess=int(guess)
        if guess>100:
            print('Enter number between 0 to 100')
        elif guess>random:
            print('your number is large')
        elif guess<random:
            print('Your number is small')
        else:
            print('Congratulation you won')
            break
    except:
        print("Enter in correct format")
        
   

Summery

In summery we learn about python loop and iteration from basic to advance. Here is a list what we learn from this article.

  • introduction of for loop
  • Some example of operation in a loop
    • Find Largest Value Through Loop
    • Counting in Loop
    • Sum on loop
    • Finding Average Value in Loop
    • Filter in loop
  • Introduction of while loop
    • python Infinite Loop
    • Break and Continue
  • Range Function
  • Project

Conclusion

Ok, this is the end of the article I hope you you can get a good lesson what I deliver in this article. I ask forgiveness for any word and behave which are not to be. Thank you for your kind and attention guys. Stay tuned for the next article. if you want to learn python from the beginning here is a link for a free course. Here is link for face mask detection project. If you have any question regarding this article please feel free to comment below.

Leave a Reply