我正在做一个原始数字猜谜游戏。下面是我的代码:
number = 68
counter=0
limit=3
guess = input("Guess the number from 1 to 100:")
while counter < limit:
if int(guess) != number:
counter+=1
if int(guess) < number:
guess = input("Too low, try again:")
if int(guess) > number:
guess = input("Too high, try again:")
if int(guess) == number:
print("You won!")
break
它一直要求我输入超过3次,并且程序不会停止工作,直到我输入较低的数字3次,反之亦然。怎么解呢?
if int(guess) < number:
guess = input("Too low, try again:")
if int(guess) > number:
guess = input("Too high, try again:")
这是有问题的,因为您接受输入,然后重新检查新的输入/数字。这应该是if/else语句。
number = 68
counter=0
limit=3
guess = input("Guess the number from 1 to 100: ")
while counter < limit:
if int(guess) != number:
counter += 1
if int(guess) < number:
guess = input("Too low, try again:")
else:
guess = input("Too high, try again:")
if int(guess) == number:
print("You won!")
break
可以看到,if
语句已经变成了else
语句。
你必须用"elif"命令。在第一个if部分中,您取2个预测并增加计数器1次。
正如之前提到的问题是你的if条件,但我会进一步优化它:
number = 68
counter = 0
limit = 3
input_message = "Guess the number from 1 to 100: "
final_message = "You lost"
while counter < limit:
guess = int(input(input_message))
if guess == number:
final_message = "You won!"
break
if guess < number:
input_message = "Too low. Try again: "
else:
input_message = "Too high. Try again: "
counter += 1
print(final_message)