簡體   English   中英

如何重復while循環一定次數

[英]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

要重復一定次數,您可以:

  1. 使用rangexrange

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

     i = 0 while i < n: # do something here i += 1 
  3. 如果循環變量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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM