raw_input检查以允许重新启动相同的功能

时间:2013-12-08 21:24:21

标签: python raw-input

我在这张桌子上撞着我的桌子,因为我是个白痴,我终于让它上班了。这是我的实际代码的简化版本(这就是为什么函数的目的看起来很愚蠢)但我很好奇是否(或者更确切地说,确定必须有)更有效的方法来执行以下操作: / p>

def get_char():
    character = raw_input("Enter the character you would like to use.\n >")
    if character.isalpha:
        proceed = raw_input("The value entered is " + character + "\nWould you like to proceed?(Y/N)\n>")
        while True:
            if proceed in "N,n":
                raw_input("Press enter to try again with another value.")
                character = get_char()
                break
            else:
                break
    return character
    #print character

character = get_char()
print character

我最终想要的是一种检查用户输入是否符合预期的方法。直到我在while循环中设置了character = get_char(),我得到了有问题的输出(即字符的最终值不正确);我已经注意到,如果我在get_char()定义的末尾包含print语句,它会打印出“no”选择+1的次数。虽然最终结果仍然很好,但我很好奇是否它似乎在队列中持有迭代这一事实,如包含print语句时的多个打印所示,这意味着有更好的方法来执行此操作。在此先感谢您的帮助!

更新: 为了防止其他人需要帮助解决同样的问题,根据millerdev的建议,我已经将代码调整为以下内容,除了没有自调用生成不必要的character排队之外,它的工作原理相同:

def get_char():
    while True:
        character = raw_input("Enter the character you would like to use\n >")
        if character.isalpha:
            proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/N)\n>")
            if proceed in ("N", "n"):
                raw_input("Press enter to try again with another value.")
            else:
                break
#print character    
return character

character = get_char()

2 个答案:

答案 0 :(得分:0)

这是你的目标吗?

def get_char():
    while True:
        character = raw_input("Enter the character you would like to use.\n >")
        if character.isalpha: # this is always true; add parens if that's what you want, otherwise remove it
            proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/n)\n>")
            if proceed.lower() == "n":
                raw_input("Press enter to try again with another value.")
                character = get_char()
            return character

character = get_char()
print character

答案 1 :(得分:0)

由于character = get_char(),您的循环只运行一次,因为如果失败而不是再次迭代,它会更深入地递归。这可能不是你想要的,因为它更慢并且冒着堆栈溢出的风险。最简洁的方法可能是(你可以轻松地用你的信息替换我的信息):

def get_char(is_valid = lambda c: True):
    while True:
        c = raw_input('enter a character > ')
        if is_valid(c):
            keep = raw_input('do you want to use {0}? (Y/N)> '.format(c)).lower()
            if 'n' in keep:
                continue # go back to While True line
            return c
        print('{0} is not a valid character'.format(c))

会话:

>>> get_char()
enter a character > a
do you want to use a? (Y/N)> n
enter a character > c
do you want to use c? (Y/N)> no
enter a character > x
do you want to use x? (Y/N)> y
'x'

至少,这是我认为最干净的。您的实现还有一些其他问题,例如proceed in "N,n",它们也会将逗号计为n,如果该字符不是isalpha,您仍会将其返回。