如何停止重复我的函数循环的开始

时间:2014-11-29 18:47:12

标签: python function python-3.x python-3.4

我已经创建了一个代码,用户将在其中输入他们的选择,如果变量'contin'等于“yes”,它将在循环中继续。当用户输入选择“否”或任何其他输入时,它将打印其总体答案或错误消息并结束循环。相反,它会重复函数的开头(在这种情况下,用户是否想要继续)。我有办法防止这种情况发生吗? 这是代码:

def userinput():

    while True:
        contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
        if contin == 'yes':
            print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']

            guess = input("What symbol do you wish to change? ")

            symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")

            print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])

        elif contin == ('no'):
            print ("These were your overall answers:")
            print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])

            if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
                         "4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
                         "%":"N", "2":"S", ":":"T", "1":"O",",":"J",
                         "$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
                         "'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
                print("Well done! You have completed the game!")

        else:
            print("Please enter a valid input.")

2 个答案:

答案 0 :(得分:1)

您需要做的就是退出该功能;在return分支中添加no

elif contin == ('no'):
    print ("These were your overall answers:")
    print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])

    if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
                 "4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
                 "%":"N", "2":"S", ":":"T", "1":"O",",":"J",
                 "$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
                 "'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
        print("Well done! You have completed the game!")

    # exit the function
    return

答案 1 :(得分:0)

只需在elif语句末尾添加一个中断或返回:

print("Well done! You have completed the game!")
break # or return

这将退出循环。在这种情况下,休息更有意义。