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

4

想象一下:

你有一个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个回答

14
count = 0

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


print count

好的回答,我会看看其他的。 - Turbo

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

1
或者为了节省内存,可以使用sum(1 for _ in iter(...))代替len(list(iter(...))) - Steve Jessop
2
@SteveJessop -- 虽然你是对的...如果数据确实来自input,我怀疑用户不会输入足够多的数字来影响系统的总内存使用量... - mgilson
@mgilson:当然,如果你要使用生成器,通常你会想知道如何避免中间列表。无论在这种情况下你是否需要避免它都与乐趣无关!这实际上只是一个问题,你更喜欢yes 0 | ./guessing_game.py多快出错。 - Steve Jessop
哈哈,这是那种“如果你有一把锤子,所有东西看起来都像钉子”的答案之一 :P 我只是真的很喜欢那个迭代器技巧。 - Joran Beasley

4

一个选项是将其转化为

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()

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

0

非常简单的方法是让计数器在条件为真或假时加1,您可以按照自己的方式或需要使用它。此外,我是一个新手。

counter = 0

while 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

打印(counter)


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