5

As seen over here, there are two ways to repeat something a number of times. But it does not seem to work for me, so I was wondering if anybody could help.

Basically, I want to repeat the following 3 times

 import random
 a = []
 w = 0

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

Based on what the link says, this is what I did,

 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

But this doesn't seem to work. The while loop only repeats once instead of three times. Could anybody help me fix this problem?

Artus
  • 165
  • 1
  • 2
  • 7
  • 4
    Put w=0 inside outer loop – Ruslanas Balčiūnas Jan 13 '18 at 12:09
  • 1
    Or even better use: for r in range(3): for w in range(4): – R2RT Jan 13 '18 at 12:10
  • [A tutorial](https://www.w3schools.in/python-tutorial/loops/) might help you understand the logic of Python loops. You can visualise the execution of your Python program [on Pythontutor](http://pythontutor.com/visualize.html#mode=edit). This allows you to observe intermediate variables and execute your program step by step. – Mr. T Jan 13 '18 at 12:44

3 Answers3

10

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

  1. Use range or xrange

    for i in range(n):
        # do something here
    
  2. Use while

    i = 0
    while i < n:
        # do something here
        i += 1  
    
  3. If the loop variable i is irrelevant, you may use _ instead

    for _ 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
Roll
  • 289
  • 1
  • 5
4

As stated by @R2RT, 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
Tinsten
  • 356
  • 2
  • 15
3

I dont see the

w=w+1

in your code, why you removed that? Add w=w+1 before r=r+1.

Good luck.

Max
  • 31
  • 1
  • I actually did write w = w+1 in the actual code. I just forgot to write it here. Thanks for letting me know. :) I will edit. – Artus Jan 13 '18 at 12:15
  • 1
    @Max You must reset w to 0 after leaving internal `while` – R2RT Jan 13 '18 at 12:28