作为我大学类(class)的一部分,我正在学习 python,我一直在尝试(重新)编写这个猜数字游戏,如果用户在 5 次尝试内未能正确猜出,该游戏将终止:
# Guess My Number Mod 5 tries or bust
import random
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in five tries or less")
my_number = random.randint(1, 100)
guess = int(input("Go on, Take a guess, I dare ya "))
tries = 1
while guess != my_number:
if guess > my_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Go on, Take a guess, I dare ya "))
tries += 1
if tries==5:
input("You failed to guess the number was it that hard?\n Press any key to exit!)"
print("Well done you guessed correctly!The number was", my_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
我假设终止原因不起作用,因为我的 if 语句在 while 循环之外,我无法让它生效。
还有一些无效的语法,因为我累了,无法发现它。
如果可能的话,你们能给我一些提示,告诉我如何解决我想做的事情,因为我更有可能以这种方式学习。
最佳答案
您正在寻找 break 满足特定条件时退出循环。
if condition:
# do something
break # brings you out of the loop
关于python - 在有限的尝试游戏中猜猜我的号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294225/