For loop vs While loop python - codebugfree

 In this section we learn difference between while loop and for loop. Basically loop is use to program run automatically until stop the programmer or any condition meet and stop.

For loop vs while loop

Loop is basically two types they are for loop and while loop. Mainly see as beginner programmer for loop is best for use. High chance to use for loop in beginner programmer. low chance to use while loop in beginner programmer.

Advance programmer use for loop and while loop equally. In some case their is chance to use for loop more than while loop.

For loop  

Mainly for loop is use as a range or iterate the value. According to my vision code bug free more use for than while loop.

For loop is use as a range system suppose you give range 0 to 5 than loop run 5 times 0,1,2,3,4 at last 5 value is escape.

for i in range(0,5):
    print(i)

INOUTPUT

0
1
2
3
4

It is a syntax and example of for loop. For loop make readable than while loop. Now we make the multiplication table of 10 using the for loop

Multiplication_of_10 = 10
for i in range(1,11):
    print(f"{Multiplication_of_10} x {i} = {i*Multiplication_of_10}")

INOUTPUT

10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

It is a for loop python project. east to use and make the code sens and make code readability.

While loop

While loop is use as a condition. When condition meets the loop run and condition meet than loop exit. When we starting a while loop if no condition to start loop in their case use True boolen value.

number = 0
while(True):
    
    number += 1
    print(number)
    if number == 5:
        break

INOUTPUT

1
2
3
4
5

Post a Comment

0 Comments