当我有一个包含continue语句的函数时,即使它只在while循环中使用,也会出错

2024-04-25 06:21:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

如何将该函数与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行 持续 ^ SyntaxError:“continue”在循环中不正确


1条回答
网友
1楼 · 发布于 2024-04-25 06:21:08

听起来您可能不熟悉continue关键字的用途。它只能在循环中使用。当在forwhile循环中到达continue语句时,循环中的其余语句都不会执行,循环将从下一次迭代开始继续(如果还有另一次迭代)

除非处于函数中的循环中,否则不能在函数中continue。您打算让continue语句做什么?可能您只需要return

相关问题 更多 >