close

How to repeat a while loop a certain number of times

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to repeat a while loop a certain number of times in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to repeat a while loop a certain number of times?

  1. How to repeat a while loop a certain number of times?

  2. Use range or xrangefor i in range(n): # do something hereUse whilei = 0 while i < n: # do something here i += 1If the loop variable i is irrelevant, you may use _ insteadfor _ in range(n): # do something here _ = 0 while _ < n # do something here _ += 1
  3. repeat a while loop a certain number of times

  4. Use range or xrangefor i in range(n): # do something hereUse whilei = 0 while i < n: # do something here i += 1If the loop variable i is irrelevant, you may use _ insteadfor _ in range(n): # do something here _ = 0 while _ < n # do something here _ += 1

Method 1

To repeat something for a certain number of times, you may:

  1. Use range or xrangefor i in range(n): # do something here
  2. Use whilei = 0 while i < n: # do something here i += 1
  3. If the loop variable i is irrelevant, you may use _ insteadfor _ in range(n): # do something here _ = 0 while _ < n # do something here _ += 1

As for nested while loops, remember to always keep the structure:

i = 0
while i < n:

    j = 0
    while j < m:
        # do something in while loop for j
        j += 1

    # do something in while loop for i
    i += 1

Method 2

you need to reset w after each r loop. Try writing this:

import random
 a = []
 w = 0
 r = 0


 while r < 3: 
      while w<4:
          x = random.uniform(1,10)
          print(x)
          print(w)
          a.append(w+x)
          print(a)
          w = w+1
      r += 1
      w = 0

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read