Python 3:如何在不停止函数的情况下退出循环

时间:2017-11-15 16:59:15

标签: python-3.x

我是一个完整的新手,并且在过去的5个小时内尝试解决这个问题(我自己的头脑和在线研究)。

下面是我们为模拟游戏而编写的函数的片段。我们希望提供开始新一轮的机会 - 意味着如果玩家击中" b",游戏应该在范围的开始处再次开始(0,玩家)。但是现在它只是进入范围内的下一个玩家(如果玩家1进入" b",该程序调用玩家2)

players = input(4)
if players in range(3, 9):
    for player in range(0, players):
        sum_points = 0
        throw_per_player_counter = 0
        print("\nIt is player no.", player+1, "'s turn!\n")
        print("\nPress 'return' to roll the dice.\n"
              "To start a new round press 'b'.\n"
              "Player", player+1)
        roll_dice = input(">>> ")
        if roll_dice == "b":
            player = 0
            throw_per_player_counter = 0
            sum_points = 0
            print("\n * A new round was started. * \n")

我已经尝试过返回和休息,也尝试将其全部放在另一个循环中...失败。中断和返回刚刚结束了该功能。 任何提示高度赞赏!

1 个答案:

答案 0 :(得分:1)

您可以将for循环更改为while循环。而不是使用range,使player成为计数器

players = 4
if 3 <= players < 9:  
    player = 0  # here's where you make your counter
    while player < players:
        sum_points = 0
        throw_per_player_counter = 0
        print("\nIt is player no.", player+1, "'s turn!\n")
        print("\nPress 'return' to roll the dice.\n"
              "To start a new round press 'b'.\n"
              "Player", player+1)
        roll_dice = input(">>> ")
        player += 1  # increment it
        if roll_dice == "b":
            player = 0  # now your reset should work
            throw_per_player_counter = 0
            sum_points = 0
            print("\n * A new round was started. * \n")