【问题标题】:How do I count the amount of iterations in a while loop? [duplicate]如何计算while循环中的迭代次数? [复制]
【发布时间】:2020-08-25 11:29:42
【问题描述】:

如何打印 while 循环运行了多少次?

例子:

from random import*

c=0

while c<3 :

    a=randint(1,6)

    b=randint(1,6)

    if a==b:
       print(a,b)
       c=c+1

【问题讨论】:

  • 添加一个counter 变量,每次迭代都会(无条件地)增加?

标签: python while-loop


【解决方案1】:

您可以添加另一个计数器。

from random import *
c = 0
loop_counter = 0
while c < 3:
  a = randint(1,6)
  b = randint(1,6)
  if a==b:
     print(a,b)
     c += 1
  loop_counter += 1

print(f"The loop run {loop_counter} times.")

【讨论】:

    【解决方案2】:

    通过添加一个“计数器变量”,每个循环都会增加一些东西。

    举个例子:

    from random import*
    
    c=0
    counter = 0 #define
    
    while c<3 :
        counter += 1 #add one 
        print (counter) #print
        a=randint(1,6)
    
        b=randint(1,6)
    
        if a==b:
           print(a,b)
           c=c+1
    

    您也可以在 while 循环结束后打印“计数器”以获得最终计数。

    【讨论】:

      【解决方案3】:
      from random import *
      
      c=0
      Counter=0
      while c<3 :
      
          a=randint(1,6)
      
          b=randint(1,6)
      
          if a==b:
             print(a,b)
             c=c+1
          Counter+=1
      
      print (Counter)
      

      【讨论】:

      • 我强烈建议不要使用首字母大写的变量名。这是错误的代码样式(然后它看起来像一个类计数器)
      • 通常不鼓励仅使用代码的答案。请edit 描述您所做的更改,以及您做出更改的原因。也请在代码中用 cmets 指出。请花一些时间阅读how to write good answers。
      • 如果您对答案感到满意,如果您投票,我将不胜感激。
      猜你喜欢
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2012-10-27
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多