[英]How to repeat a while loop a certain number of 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
根據鏈接顯示的內容,這就是我所做的,
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
但這似乎不起作用。 while循環僅重復一次,而不是重復三次。 有人可以幫我解決這個問題嗎?
我沒看到
w = w + 1
在您的代碼中,為什么要刪除它? 在r=r+1
之前加上w=w+1
r=r+1
。
祝好運。
如@ R2RT所述,您需要在每個r
循環之后重置w
。 嘗試這樣寫:
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
要重復一定次數,您可以:
使用range
或xrange
for i in range(n): # do something here
使用while
i = 0 while i < n: # do something here i += 1
如果循環變量i
不相關,則可以使用_
代替
for _ in range(n): # do something here _ = 0 while _ < n # do something here _ += 1
至於嵌套的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.