记录一个while循环运行了多少次?- Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20255372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Record how many times a while loop runs? - python
提问by Turbo
Imagine this:
想象一下:
You have a while loop
你有一个while循环
You want to know how many times it ran
你想知道它运行了多少次
What should you do???
你该怎么办???
Now I hear you say, what is the context?
现在我听到你说,上下文是什么?
Context:I am writing this program in Python which thinks of a number between 1 and 100, and you are to guess it. The guessing takes part in a while loop (please have a look at the code below) but I need to know how many guesses are made.
上下文:我正在用 Python 编写这个程序,它会考虑 1 到 100 之间的一个数字,你可以猜出来。猜测参与 while 循环(请查看下面的代码),但我需要知道进行了多少次猜测。
So, this is what I need:
所以,这就是我需要的:
print("It took you " + number_of_guesses + " guesses to get this correct.")
This is the complete code at Gist: https://gist.github.com/anonymous/1d33c9ace3f67642ac09
这是 Gist 的完整代码:https: //gist.github.com/anonymous/1d33c9ace3f67642ac09
Please remember: I am using Python 3x
请记住:我使用的是 Python 3x
Thanks in advance
提前致谢
采纳答案by jramirez
count = 0
while x != y::
count +=1 # variable will increment every loop iteration
# your code
print count
回答by dstromberg
counter = 0
while True:
counter += 1
# get input
# process input
# if done: break
回答by Joran Beasley
just for fun , your whole program in 4 (somewhat readable) lines of code
只是为了好玩,你的整个程序用 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
回答by user2357112 supports Monica
One option is to convert
一种选择是转换
while loop_test:
whatever()
to
到
import itertools
for i in itertools.count():
if not loop_test:
break
whatever()
If it's a while True, this simplifies to
如果是 a while True,则简化为
import itertools
for i in itertools.count():
whatever()
回答by Dorca Estela
Very very simple way to make Counter add 1 everytime a condition is true or false, you use it which ever way you like or need. Also, I'm a rookie.
每次条件为真或为假时,让 Counter 加 1 的非常简单的方法,您可以按照自己喜欢或需要的方式使用它。另外,我是菜鸟。
counter = 0
计数器 = 0
while x != y:
而 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
print(counter)
打印(计数器)

