python - 在有限的尝试游戏中猜猜我的号码

标签 python if-statement python-3.x while-loop

作为我大学类(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/

相关文章:

python - Django - 属性错误: 'module' object has no attribute 'admin'

MySQL多条if语句执行

java - Android - 将 Arch 转换为 Decimal

python - 打印所有可以导入的东西

python - 如何获得有关 Python 方法的帮助?

python - SyntaxError 在 Python 3 中不异常(exception)

python - 如何在不调用 RuntimeError 的情况下使用循环删除 Counter 对象中的条目?

python - Pandas 中 dataframe.loc() 的 Numpy 等价性是什么

python - GAE 取消订阅用户的存在

c - 'if' 应该测试 '==' 还是 '!='