【问题标题】:Basic while loops in PythonPython中的基本while循环
【发布时间】:2014-06-03 22:18:07
【问题描述】:

我一直在尝试用 Python 3.3.4 制作一个简单的游戏,在游戏开始时,我希望用户在 1 和 3 之间选择一个难度,如果他们放入了 1、2 或 3 以外的其他角色他们收到消息“无效输入”。

我已经编写了下面的代码,但是即使用户输入 1、2 或 3,我也无法使其正常运行,它会出现错误“无效输入”,我尝试过使用它各种组合都无济于事。我知道这是相当基本的,可能很简单,因为我是 Python 新手,所以我忽略了它。提前致谢。

while True:
    while True:
        cmd = input('Please select a diffuculty from 1 to 3, with three being the hardest: ')
        if cmd in (1, 2, 3):
            break
        print ('Invalid input.')
    if cmd == 1:
        dopt = 3
        continue
    elif cmd == 2:
        dopt = 4
        continue
    elif cmd == 2:
        dopt = 5
        continue

【问题讨论】:

  • 在 python 3 中,输入函数返回字符串,而不是整数。 cmd in ('1', '2', '3')?
  • 还有,没有办法离开你的最外层while...
  • 您可以使用int(input("..."))将字符串输入转换为整数。
  • @AndyG 是的,但是如果有人输入“a”,他的程序就会出现值错误。我认为他宁愿告诉用户输入是错误的。

标签: python loops python-3.x while-loop


【解决方案1】:

问题在于您的类型。 input 返回一个字符串,所以cmd 是一个字符串。然后你问cmd 是否在一个整数元组(1,2,3) 中。让我和你一起看看你的选择。

你可以改变

cmd = input("...")

cmd = int(input("..."))

这样,cmd 是一个 int,正如稍后预期的那样。这样做的问题是有人输入了一些不可解析为 int 的内容,比如 "foo",您的程序将立即退出并返回 ValueError。

试试这样的方法:

...
while True:
    cmd = input('Please select a diffuculty from 1 to 3, with three being the hardest: ')
    if cmd in ('1', '2', '3'):
        break
    print ('Invalid input.')
cmd = int(cmd)
if cmd == 1:
    dopt = 3
    continue
...

在这里,您在 cmd 验证中有一个字符串元组,而不是一个整数元组。之后,cmd 被解析为 int,你的程序按预期继续运行。

另一方面,您的 if-else 链可以替换为 dopt = cmd+2

祝你好运!

【讨论】:

  • 谢谢!这很有帮助。
【解决方案2】:

来自文档:

input([prompt])

等效于 eval(raw_input(prompt))。

raw_input([prompt]):

如果提示参数存在,则将其写入标准输出,不带尾随换行符。然后该函数从输入中读取一行,将其转换为 string(去除尾随的换行符),然后返回。

我修改了你的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

while True:
    cmd = int(input('Please select a diffuculty from 1 to 3, with three being the hardest: '))
    print("cmd:{}, type:{}".format(cmd, type(cmd)))
    if cmd not in (1, 2, 3):
        print ('Invalid input.')
        continue
    if cmd == 1:
        dopt = 3
        break
    elif cmd == 2:
        dopt = 4
        break
    elif cmd == 3:
        dopt = 5
        break

print ("cmd:{}; dopt:{}".format(cmd, dopt))

您可以使用type 了解您输入的类型。

【讨论】:

    【解决方案3】:

    您的代码有一个问题。

    1. input() 返回一个字符串,而不是整数。

    因为您的输入是 string,所以检查 string 是否在整数元组中,将不起作用:

    >>> tup = (1, 2, 3)
    >>> '1' in tup
    False
    >>> '3' in tup
    False
    

    因此,您可以将int() 转换为您的input(),以便将整数和仅整数作为输入:

    >>> x = int(input())
    4
    >>> type(x)
    <class 'int'>
    >>> x = int(input())
    'hello'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: "'hello'"
    >>> 
    

    因此,您可以检查输入是否在您的元组中:

    >>> tup = (1, 2, 3)
    >>> x = int(input())
    2
    >>> x in tup
    True
    >>> x = int(input())
    7
    >>> x in tup
    False
    >>> 
    

    这是您编辑的代码:

    while True:
        while True:
            cmd = int(input('Please select a diffuculty from 1 to 3, with three being the hardest: '))
            if cmd in (1, 2, 3):
                break
            print ('Invalid input.')
        if cmd == 1:
            dopt = 3
            continue
        elif cmd == 2:
            dopt = 4
            continue
        elif cmd == 2:
            dopt = 5
            continue
    

    【讨论】:

    • input 可以返回一个int,实际上它甚至可以返回一个list。输入为您解析字符串,在您希望原始输入使用... raw()
    • @CristianGarcia, raw_input()python-3.x 中不存在
    • ohhhh... 然后忽略我的评论 ;)
    猜你喜欢
    • 2014-11-02
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多