Python 当我有一个包含continue语句的函数时,即使它只在while循环中使用,也会出错
如何将该函数与continue语句一起使用?或者任何其他方法来避免我重复那段代码。我是python新手,我需要添加足够的单词来发布这篇文章。谢谢所有帮助我的人:) 错误消息: C:\desktop 2\files\Python projects\rock paper scissors\Method2>gamelooped.py 文件“C:\desktop 2\files\Python projects\rock paper Scissors\Method2\gamelooped.py”,第9行 持续 ^Python 当我有一个包含continue语句的函数时,即使它只在while循环中使用,也会出错,python,function,while-loop,Python,Function,While Loop,如何将该函数与continue语句一起使用?或者任何其他方法来避免我重复那段代码。我是python新手,我需要添加足够的单词来发布这篇文章。谢谢所有帮助我的人:) 错误消息: C:\desktop 2\files\Python projects\rock paper scissors\Method2>gamelooped.py 文件“C:\desktop 2\files\Python projects\rock paper Scissors\Method2\gamelooped.py”,第9行
语法错误:“continue”在循环中不正确听起来您可能不熟悉
continue
关键字的用途。它只能在循环中使用。当您在for
或while
循环中到达continue
语句时,循环中的其余语句都不会执行,循环将从下一次迭代开始继续(如果还有另一次迭代)
除非处于函数中的循环中,否则不能在函数中
继续。您打算让该continue
语句执行什么操作?您可能只需要返回
您好,您能在问题中完整地包含您收到的错误消息吗?当您在线发布涉及错误消息的问题时,请始终包含错误消息。请使用引号或代码块并将所有错误放在内部我希望continue语句从while循环的顶部开始。我想让用户说他们是否想继续玩游戏,如果答案是“是”,游戏将从头开始。@RobbyS Acontinue
仅在循环内有意义,而不是在函数中,即使函数仅从循环内调用。例如,如果你调用函数而不是在一个循环中会发生什么?@ Rabbys考虑从函数返回一个布尔值,并按照代码执行< <代码>中断> /代码>或<代码>继续< /代码>。这是语言的约束:如果你处于一个被循环调用的函数中,您不能在函数中使用continue
关键字。只能在循环本身中使用continue
。你必须返回一些值,比如False
,并且在循环中有一个if
语句来决定你是否应该继续
。哦,你是说我应该只存储用户是否给出了是或否,如果是,那么我就可以在循环本身中退出或中断。非常感谢。
all_options = ["rock", "paper", "scissors"]
outcomes = {"rockP": ["paper", "computer"], "rockS": ["scissor", "player"], "paperR": ["rock", "player"], "paperS": ["scissor", "computer"], "scissorsR": ["rock", "computer"], "scissorsP": ["paper", "player"]}
input_loop = True
def play_again():
again = input("Would you like to play again?(Yes or No): ")
if again.lower() == "yes":
continue
elif again.lower() == "no":
exit()
else:
print("Invalid input. Exiting")
exit()
while True:
while input_loop == True:
choice = input("Please input Rock, Paper, or Scissors: ")
if choice.lower() in all_options: #Making sure that the input is lowercase so it doesn't error
choice = choice.lower()
input_loop = False
break
else:
print("\n That is not a valid input \n")
computer_choice = random.choice(all_options)
if choice == computer_choice:
print("Draw!")
play_again()
computer_choice = computer_choice.upper()
current_outcome = choice + computer_choice
current_outcome_list = outcomes.get(current_outcome)
current_outcome_list.insert(0, choice)
player, winner, outcome = current_outcome_list
winning_message = print(f"{winner} has won, \nplayer chose: {player}, \ncomputer chose: {computer}.")
print(winning_message)
play_again()