2014-12-05 49 views
0

我想在python中做一個「數字猜測遊戲」,並且我希望它顯示用戶爲了猜測計算機在最後生成的隨機數而必須作出的猜測次數。這裏是我迄今爲止給我的意思的例子:如何跟蹤python中while循環的輸入數量?

from random import* 
a=randrange(1,51) 
b=int(input("Can you guess my number?: ")) 
while a>b: 
    b=int(input("Too low, try again: ")) 
while a<b: 
    b=int(input("Too high, try again: ")) 
while a==b: 
    print("You got it! The number was", a) 
    break 

我想它打印的東西,如「你花了__猜測」結尾。我將如何去追蹤像這樣的輸入數量?我試着四處尋找,但我不確定如何將它寫入文字。

+1

首先,這段代碼沒有做你想做的事。假設您輸入的數字太低,然後輸入的數字太高,最後輸入的數字太低。你的代碼會過早終止。 – irrelephant 2014-12-05 06:02:17

+0

我現在看到了,謝謝。 – zodian 2014-12-05 06:30:44

回答

2

你想要做的就是擺脫3個while循環和while循環內改變他們if語句什麼:

from random import* 
a=randrange(1,51) 
b = 0 
guesses = 0 #Initialize a variable to store how many guesses the user has used 
while b != a: 
    b=int(input("Can you guess my number?: ")) 
    if a>b: 
     b=int(input("Too low, try again: ")) 
    else: 
     b=int(input("Too high, try again: ")) 
    guesses+=1 

print("You got it! The number was", a) 
print("You took {} guesses!".format(guesses)) 
1

猜想跟蹤沒有。的猜測

from random import* 

a=randrange(1,51) 
guess = 0 
while True: 
    b=int(input("Can you guess my number?: ")) 
    guess += 1 

    if b==a: 
     print("You got it correct") 
     break 

    elif b>a: 
     print("number is higher") 

    else: 
     print("number is lower") 

print("Guesses: ", guess) 
0

d = 74 數= 1

def check(n): if n==d: count += 1 print "You Got the number" elif n>d:
print "The number is too high" count += 1 check(int(raw_input('Enter another number'))) elif n<d:
print "The no is too low" if count count += 1 check(int(raw_input('Enter something high'))) return count

返回的值是猜測的數量