用户输入的while循环不会退出

时间:2015-05-12 05:06:18

标签: python

当我输入exitCode时,下面的代码没有停止,另一个问题是elif行检测到作为数字输入的每个字符。

counter = 0
exitCode = 'X'
wantsToExit = False

while counter < 6 and wantsToExit == False:
        candyName = str(input('Enter the candy\'s code/name ({0} to exit): '.format(exitCode)))
        if candyName == "{0}".format(exitCode):
            wantsToExit == True
            print("You have chosen to exit.")
        elif candyName.isdigit:
            print("Please only enter letters.")

3 个答案:

答案 0 :(得分:4)

您的代码存在一些问题。

正如Dzarafata所说,

  1. 您正在counter循环顶部测试while的值,但您永远不会在循环中更改其值。
  2. elif candyName.isdigit: 不会测试字符串candyName是否只包含数字。要做到这一点,您需要实际调用方法,如下所示:elif candyName.isdigit() 但是,这可能不是您真正想要的测试,因为它不会捕获包含不是数字的非字母的字符串,例如标点符号。
  3. FWIW,if candyName.isdigit:测试candyName.isdigit方法本身的真值。在Python中,方法是一个对象和任何不等同于0FalseNone或其他空对象的对象,如空字符串,列表,元组,集合, dict等被认为是True。所以

    if candyName.isdigit:
        print("stuff")
    

    始终打印stuff,无论candyName中的字符串是什么。

    您的代码的第3个问题是,当它获得正确的数据时,它不会从while循环退出。

    代码中的一个小缺陷是str(input(stuff))。 Python 3 input()函数总是返回一个字符串,因此不需要将其输出转换为str()的字符串。但是如果您使用的是Python 2,那么您应该避免使用input()并使用raw_input(),因为Python 2 input()可以使用不受信任的输入做危险的事情。

    以下是您的代码的修改版本。我已将candyName更改为candy_name以符合通常的Python命名约定。我已修改逻辑以使用break语句,因此我们不再需要wantsToExit标记。

    exitCode = 'X'
    prompt = "Enter the candy's code/name ({0} to exit): ".format(exitCode)
    
    #Make upto 6 attempts to get correct input
    candy_name = None
    for counter in range(1, 7):
        data = input("{0}: {1}".format(counter, prompt))
        if data == exitCode:
            print("You have chosen to exit.")
            break
        elif not data.isalpha():
            print("Please only enter letters.")
        else:
            candy_name = data
            break
    
    if candy_name is None:
        print("No valid candy name was entered")
    else:
       print("Candy name: '{0}'".format(candy_name))
    

    请注意,我使用data来存储用户输入字符串,只有在我们确定它是有效名称后才会将其复制到candy_name。此版本还会在提示开始时打印counter的当前值。

答案 1 :(得分:1)

更改这些行:

wantsToExit == True
elif candyName.isdigit:

为:

wantsToExit = True
elif candyName.isdigit():    

另外:你的循环一直持续到计数器为&lt; 6所以你必须通过counter += 1

在每次迭代中使它变大

答案 2 :(得分:0)

纠正这一行:

 wantsToExit == True
 elif candyName.isdigit:

对此:

 wantsToExit = True
 elif candyName.isdigit():
相关问题