如何重复执行while循环特定次数

5

此处所示,有两种方式可以重复执行某些操作。但对我来说好像不起作用,所以我想知道是否有人可以帮助我。

基本上,我想要将以下内容重复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循环仅重复一次,而不是三次。有人可以帮我解决这个问题吗?


4
在外层循环中将w=0。 - Ruslanas Balčiūnas
1
甚至更好的是使用:for r in range(3): for w in range(4): - R2RT
一份教程可能会帮助您理解Python循环的逻辑。您可以在Pythontutor上可视化执行Python程序。这使您能够观察中间变量并逐步执行程序。 - Mr. T
3个回答

10
为了重复某个操作若干次,您可以采取以下方法:
  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
    

关于嵌套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

4
如@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

3

我在你的代码中没有看到

w=w+1

这一句,为什么你把它删掉了? 在 r=r+1 之前添加 w=w+1

祝你好运。


实际上我在代码中确实写了 w = w+1。我只是忘记在这里写了。谢谢你让我知道。 :) 我会进行编辑。 - Artus
1
@Max 在离开内部的 while 后,你必须将 w 重置为 0。 - R2RT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接