Python 如何停止函数的开始';使循环不重复
我已经创建了一个代码,用户将在其中输入他们的选择,如果变量“contin”等于“yes”,则该选择将在循环中继续。当用户输入选择“否”或任何其他输入时,它将打印他们的总体答案或错误消息,并结束循环。相反,它会重复函数的开头(在本例中,是用户是否希望继续)。我有没有办法防止这种情况发生? 代码如下:Python 如何停止函数的开始';使循环不重复,python,function,python-3.x,python-3.4,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 en
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.")
您只需退出该功能;在
no
分支中添加一个return
:
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
只需在elif语句末尾添加一个中断或返回:
print("Well done! You have completed the game!")
break # or return
这将退出循环。在这种情况下,Break更有意义。我建议您使用注释、
pass
或其他方式替换与问题毫无共同之处的代码;这会使你的问题更容易理解。这对我帮助很大。我刚开始计算机科学的普通中等教育证书,我的老师从来没有教过我这个。谢谢:3