[英]how do I keep track of the number of inputs for a while loop in python?
我正在嘗試用python創建一個“數字猜謎游戲”,並且我希望它顯示用戶為猜測最后由計算機生成的隨機數而必須進行的猜測的數目。 到目前為止,這里是我所要表達的示例:
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
我希望它在最后打印類似“花了您__個猜測”的內容。 我將如何跟蹤這樣的輸入數量? 我嘗試四處搜尋,但是我不確定如何將它寫成文字。
您想要做的是擺脫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))
猜測保持否。 猜測
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)
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
返回的值是猜測數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.