【问题标题】:Trying to have a Python program quit with the letter "q", but input is an integer? [duplicate]试图用字母“q”退出 Python 程序,但输入是整数? [复制]
【发布时间】:2018-07-24 15:54:39
【问题描述】:

下面代码的快速sn-p。我试着弄乱another answer posted on here,但它似乎根本不起作用。我不确定我做错了什么。在 Xubuntu 18.04 LTS 上使用 Python 3。代码如下:

while True:
    try:
        print("Your room is DARK, yet a light flashes red. What do you do?")
        print("")
        print("1. Look around.")
        print("2. There's a lamp somewhere...")
        print("3. Go back to bed.")
        print("")
        ans = int(input(">>> "))
        if ans == 1:
            print("")
            print("Too dark to see... better find a light...")
            time.sleep(2)
        if ans == 2:
            print("")
            print("Fumbling, you turn on your nightstand lamp...")
            break
        if ans == 3:
            print("")
            print("You sleep away the troubles... but you can't stay asleep...")
            time.sleep(1)
            print("")
            print("Back to the world of the living...")
        if ans == str('q'):
            sys.exit(0)
    except ValueError:
        print("")

所以,当用户输入“q”时,我希望程序关闭。我似乎根本做不到。

【问题讨论】:

  • ans = int(input(">>> ")) - 这是试图将其转换为整数。因此你永远不会得到ans == str('q')(另请注意str('q') == 'q'...)
  • 为什么要转换成整数?将其保留为字符串并与“1”、“2”、“3”和“q”进行比较。
  • 我不得不承认我觉得自己像个彻头彻尾的白痴。我不知道为什么要将所有内容都转换为整数。将其作为字符串要简单得多。

标签: python string python-3.x ubuntu integer


【解决方案1】:

问题在于您所说的int(input(">>> ")) 将用户每次输入的内容转换为整数。你应该做的是将用户输入作为一个字符串,然后检查它是否是 1、2 和 3 的有效数字,或者它是否等于 q。

例子:

ans = input(">>> ")
if ans == '1':
    # Do something
elif ans == '2':
    # Do something
elif ans == '3':
    # Do something
elif ans == 'q':
    sys.exit(0)

【讨论】:

    【解决方案2】:

    您在输入时将 q 类型转换为整数:ans = int(input(">>> ")),然后尝试将其类型转换回 if ans == str('q'): 处的字符串更好的解决方案是将输入作为字符串保留在 ans 中(删除 @987654323 @ 类型转换并在每种情况下将其显式类型转换为带有 int() 的 int。

    更新:我原来的解决方案是错误的。更正后的询问字符串是否为数字,然后将其评估为 int。这更冗长,因此我推荐 Karl 的解决方案。但是,如果您热衷于将字符串类型转换为 int,我将在此发布。

    while True:
    try:
        ans = input(">>> ")
        if ans.isdigit() and int(ans) == 1:
            ...
        elif ans.isdigit() and int(ans) == 2:
            ...
        elif ans.isdigit() and int(ans) == 3:
            ...
        elif ans == 'q':
            sys.exit(0)
    except ValueError:
        print("")
    

    那你根本不需要打电话给str()

    【讨论】:

    • 我觉得这是最好的解决方案。谢谢你。不过,你们所有人都是对的,尝试按照我原来的方式去做是很愚蠢的。我觉得自己像个彻头彻尾的白痴。大声笑但是谢谢你的帮助!
    • 我的解决方法不对。
    • @M.我会尽快删除这个答案。但这是错误的。输入 q 会导致错误,因为我将字母转换为数字。
    • @M.我纠正了它。但我的建议是坚持 Karl 的回答。
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多