Reputation: 173
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?
Upvotes: 6
Views: 73148
Reputation: 299
To repeat something for a certain number of times, you may:
Use range
or xrange
for i in range(n):
# do something here
Use while
i = 0
while i < n:
# do something here
i += 1
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
Upvotes: 11
Reputation: 356
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
Upvotes: 4
Reputation: 31
I dont see the
w=w+1
in your code, why you removed that?
Add w=w+1
before r=r+1
.
Good luck.
Upvotes: 3