2013-11-27 38 views
2

想象一下:記錄while循環運行多少次? - 蟒蛇

你有一個while循環

你想知道有多少次跑到

你應該怎麼辦???

現在我聽到你說,是什麼情況?

語境: 我用Python寫這個計劃,認爲1和100之間的數字,而且你猜它。猜測參與了一個while循環(請看下面的代碼),但我需要知道做了多少猜測。

所以,這是我需要的:

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

這是吉斯特的完整代碼:https://gist.github.com/anonymous/1d33c9ace3f67642ac09

請記住:我使用Python 3倍提前

謝謝

回答

5
count = 0 

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


print count 
+0

不錯的答案,我會看看其他人 – Turbo

+0

你知道爲什麼這個問題是downvoted嗎? – Turbo

+0

它在我看來不像它是downvoted。 – jramirez

2
counter = 0 
while True: 
    counter += 1 
    # get input 
    # process input 
    # if done: break 
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(...)))''。 –

+2

@SteveJessop - 雖然你是正確的...如果數據實際上來自'輸入',我懷疑用戶是否打算輸入足夠的數字來減少系統的總內存使用量...... – mgilson

+0

謝謝不知道爲什麼我這樣做:P –

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

我感謝你的努力,所以我投了贊成票。 – Turbo