我试图制作一个猜数游戏"在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
我希望打印类似于&#34的东西;它花了你__猜测&#34;在末尾。我将如何跟踪这样的输入数量?我试着四处寻找,但我并不确定如何将它写成文字。
答案 0 :(得分:2)
您要做的是摆脱3个while
循环,并将其更改为if
循环中的while
个语句:
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 :(得分: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)
答案 2 :(得分:0)
d = 74 count = 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
返回的值是猜测次数