import random
random_num = random.randint(1, 100)
count = 1
while True:
try:
num = int(input("Guess the number? "))
if num == random_num:
print("Congrates! you guessed it.")
print("Tried:", count, "times")
play = input("Do you want to play again Y/N? ")
if play.lower() in ['n', 'no']:
quit()
elif play.lower() in ['y', 'yes']:
random_num = random.randint(1, 100)
count = 1
else:
quit()
elif num > random_num:
print("Not yet, smaller.")
elif num < random_num:
print("Not yet, Greater.")
else:
quit()
count += 1
except:
print("Oops! please enter a valid number.")
当我运行此代码时,它运行正常。但是当我完成游戏并选择不再玩时,它陷入了无限循环
当我运行好并选择 n 或 no 时,它陷入无限循环
Guess the number? Oops! please enter a valid number.
永远,但我期待的是完成游戏并结束程序。
正如@Cincinnatus 评论的那样,使用
break
语句退出循环应该可以解决这个问题。或者,您可以尝试建立一个变量来维护循环的当前“运行”状态。这是调整为使用此模式的代码:
import random
random_num = random.randint(1, 100)
count = 1
running = True
while running:
try:
num = int(input("Guess the number? "))
if num == random_num:
print("Congrates! you guessed it.")
print("Tried:", count, "times")
play = input("Do you want to play again Y/N? ")
if play.lower() in ['n', 'no']:
running = False
elif play.lower() in ['y', 'yes']:
random_num = random.randint(1, 100)
count = 1
else:
running = False
elif num > random_num:
print("Not yet, smaller.")
elif num < random_num:
print("Not yet, Greater.")
else:
running = False
count += 1
except:
print("Oops! please enter a valid number.")