首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使代码向后跳转而不是向前跳转?

如何使代码向后跳转而不是向前跳转?
EN

Stack Overflow用户
提问于 2021-07-12 13:35:48
回答 1查看 41关注 0票数 0

我正在处理一个策划者任务,但是我的一个定义函数没有按预期工作。

我如何让“退出”跳回“猜一猜...”而不是继续到colourlst?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-12 13:59:46

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

代码语言:javascript
复制
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],强制只接受一个字符。完整的“yes”或“no”也有效;-)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68342343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档