你想问的第一件事是当你print tries
,你得到什么?实际上,你会看到你总是得到 1。
因为,你没有增加。您没有添加,因为用户一直在猜测。
一般来说,你可以tries = tries + 1
为每个猜测写。
tries = 1
while number != secretNumber:
if number > secretNumber:
print("Too high!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
if number < secretNumber:
print("Too low!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
while number == secretNumber:
print("You got it in",tries,"tries")
break
这段代码仍然有一些问题。第二个循环没有意义。循环听起来像循环。它会一直运行,直到满足条件或有人(你)打断它并告诉它退出。
如果用户找到了号码,那么while number !- secretNumber
会变成False
对的吗?它将退出第一个循环。因此,您可以跳过第二个循环并祝贺用户。
另一件小事是双重if
陈述。
if
声明很昂贵。计算机必须测试才能猜对。但无论哪种方式,都有不同的方法来处理多个条件。
if condition1 met:
do this
elif condition2 met:
do this
elif condition3 met:
do this
elif more....
else: # optional, but encourage, this is a default fallback case
do this
如果number > secretNumber
是True
,那么您不需要进行number < secretNumber
理论上的测试。它通过适应使代码更清晰和逻辑合理if .. elif .. else
import random
secretNumber = random.randint(1,100)
secretNumber = int(secretNumber)
print("Guess a number between 1 and 100!")
number = input("Your guess: ")
number = int(number)
tries = 1
while number != secretNumber:
if number > secretNumber:
print("Too high!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
elif number < secretNumber:
print("Too low!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
print("You got it in",tries,"tries")
# another way to print is
# print("You got it in %s tries" % tries)
# print("You got it in {t} tries".format(t=tries))
对于初学者,用于print
帮助调试您的代码。