[英]How to repeat a while loop a certain number of times
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 基本上,我想重复以下3次
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.
while循环仅重复一次,而不是重复三次。 Could anybody help me fix this problem?
有人可以帮我解决这个问题吗?
I dont see the 我没看到
w=w+1
w = w + 1
in your code, why you removed that? 在您的代码中,为什么要删除它? Add
w=w+1
before r=r+1
. 在
r=r+1
之前加上w=w+1
r=r+1
。
Good luck. 祝好运。
As stated by @R2RT, you need to reset w
after each r
loop. 如@ R2RT所述,您需要在每个
r
循环之后重置w
。 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
To repeat something for a certain number of times, you may: 要重复一定次数,您可以:
Use range
or xrange
使用
range
或xrange
for i in range(n): # do something here
Use while
使用
while
i = 0 while i < n: # do something here i += 1
If the loop variable i
is irrelevant, you may use _
instead 如果循环变量
i
不相关,则可以使用_
代替
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: 至于嵌套的
while
循环,请记住始终保持以下结构:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.