【问题标题】:How to make the code jump back instead of forward?如何让代码向后跳转而不是向前跳转?
【发布时间】:2021-07-12 05:35:47
【问题描述】:

我正在处理一项策划任务,但我的定义功能之一没有按预期工作。

如何让“退出”跳回“猜一猜...”而不是继续到第一个颜色?

def valid_usercolour():
    while True:
        #print('Welcome to the Mastermind') 
        usercolour = input('Please have your guess [r,o,y,g]: ').lower()
        if 'quit' in usercolour:    
            while True:
                dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
                if dc_quit.lower() == "y":
                    print()
                    print('Alright, thank You for playing, Goodbye', user_name, '!' )
                    quit()
                    break 
                elif dc_quit.lower() == "n":
                    print("Alright, let's continue to our game")
                    break
                else:
                    print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
                    continue
                      
        colourslist = ['r','o','y','g']
        if any(character not in colourslist for character in usercolour):
            print("Error! Only Characters ,", colourslist, "are allowed")
            continue
        if len(usercolour) != 4:
            print("Error! Only 4 characters are allowed!")
            continue
        break
    return usercolour

【问题讨论】:

  • 中断和继续只适用于最内层循环

标签: python loops if-statement while-loop


【解决方案1】:

只需添加else: 并在colourslist 之前缩进它下面的内容。 Python 代码不会“跳回”:

def valid_usercolour():
    while True:
        #print('Welcome to the Mastermind') 
        usercolour = input('Please have your guess [r,o,y,g]: ').lower()
        if 'quit' in usercolour:
            while True:
                dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
                if dc_quit[0].lower()[0] == "y":
                    print()
                    print('Alright, thank You for playing, Goodbye', user_name, '!' )
                    quit()
                    break 
                elif dc_quit[0].lower()[0] == "n":
                    print("Alright, let's continue to our game")
                    break
                else:
                    print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
                    continue
        else:                      
            colourslist = ['r','o','y','g']
            if any(character not in colourslist for character in usercolour):
                print("Error! Only Characters ,", colourslist, "are allowed")
                continue
            if len(usercolour) != 4:
                print("Error! Only 4 characters are allowed!")
                continue
            break
    return usercolour

奖励:我在 dc_quit 的值处添加了 [0] 以强制仅使用一个字符。完整的“是”或“否”也可以;-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多