1

所以,我有这样的事情:

def pickClass():
    print('What class are you? FIGHTER, MAGE, or THIEF?')
    classChoice = raw_input()
    if classChoice == 'FIGHTER':
        print('You are a mighty warrior. Are you sure? YES or NO.')
        _confirm = raw_input()
        if _confirm == 'YES':
            print('So be it.')
        elif _confirm == 'NO':
            pickClass()
        else:
            print('YES or NO only!')
            #go back to '_confirm = raw_input()'

我被卡住的部分在最后——如何在不再次遍历整个函数的情况下进入代码的特定部分?

(我知道那张印刷品有点多余,但无论如何,maaaaan)

4

3 回答 3

3

您将需要重组您的功能。尝试这样的事情:

def pickClass():
    valid_classes = ["FIGHTER", "MAGE", "THIEF"]
    while True:
        print('What class are you? FIGHTER, MAGE, or THIEF?')
        classChoice = raw_input()
        if classChoice not in valid_classes:
            print("Invalid class")
        else:
            print("Are you sure you want to be a %s?" % classChoice)
            while True:
                _confirm = raw_input()
                if _confirm == 'YES':
                    print('So be it.')
                    return classChoice
                elif _confirm == 'NO':
                    break
                else:
                    print('YES or NO only!')
于 2012-11-21T03:53:47.757 回答
1
def pickClass():
    classChoice = None
    while classChoice is None:
        print('What class are you? FIGHTER, MAGE, or THIEF?')
        classChoice = raw_input()
        if classChoice == 'FIGHTER':
            while True:
                print('You are a mighty warrior. Are you sure? YES or NO.')
                _confirm = raw_input()
                if _confirm == 'YES':
                    print('So be it.')
                    break
                elif _confirm == 'NO':
                    break
                print('YES or NO only!')
    return classChoice

confirm制作一个可以重用于其他问题的函数可能是个好主意。注意这如何简化逻辑pickClass

def confirm(msg):
    while True:
        print(msg)
        _confirm = raw_input()
        if _confirm == 'YES':
            print('So be it.')
            return True
        elif _confirm == 'NO':
            return False
        print('YES or NO only!')


def pickClass():
    while True:
        print('What class are you? FIGHTER, MAGE, or THIEF?')
        classChoice = raw_input()
        if classChoice == 'FIGHTER':
            if confirm('You are a mighty warrior. Are you sure? YES or NO.'):
                return classChoice
于 2012-11-21T04:01:15.107 回答
0

您可以while _confirm not in['YES', 'NO']在这种情况下使用。制作功能也很有意义confirm()

于 2012-11-21T03:56:10.283 回答