记录while循环运行的次数? - 蟒蛇

时间:2013-11-27 23:53:44

标签: python loops

想象一下:

你有一个while循环

您想知道它运行了多少次

你应该怎么做???

现在我听到你说,上下文是什么?

上下文 我正在用Python编写这个程序,它想到了1到100之间的数字,你要猜测它。猜测参与了一个while循环(请看下面的代码),但我需要知道有多少猜测。

所以,这就是我需要的:

print("It took you " + number_of_guesses + " guesses to get this correct.")

这是Gist上的完整代码:https://gist.github.com/anonymous/1d33c9ace3f67642ac09

请记住:我使用的是Python 3x

提前致谢

5 个答案:

答案 0 :(得分:5)

count = 0

while x != y::
   count +=1 # variable will increment every loop iteration
   # your code


print count

答案 1 :(得分:5)

只是为了好玩,你的整个程序有4行(有些可读)代码

sentinel = random.randint(1,10)
def check_guess(guess):
    print ("Hint:(too small)" if guess < sentinel else "Hint:(too big)")
    return True

total_guesses = sum(1 for guess in iter(lambda:int(input("Can you guess it?: ")), sentinel) if check_guess(guess)) + 1

答案 2 :(得分:2)

counter = 0
while True:
   counter += 1
   # get input
   # process input
   # if done: break

答案 3 :(得分:2)

一种选择是转换

while loop_test:
    whatever()

import itertools
for i in itertools.count():
    if not loop_test:
        break
    whatever()

如果是while True,则会简化为

import itertools
for i in itertools.count():
    whatever()

答案 4 :(得分:0)

一种非常简单的方法,使条件每次为true或false时,Counter加1,您可以根据自己的喜好或需要使用它。另外,我是菜鸟。

计数器= 0

而x!= y:

if somethingHere == somethingThere:
    counter = counter + 1 
    #your code here
elif somethingHere > somethingThere:
    counter = counter + 1
    #your code here
else
    counter = counter + 1
    #your code here

打印(计数器)

相关问题