Creating a WHILE-Loop with a dynamic number of conditions in Python

30 Views Asked by At

I am looking for a solution to create a dynamic WHILE Loop. For example, if I have a game with a flexible number of players (2-6) and each player has a score, the WHILE Loop should end when one of those players reached a score of 100. I had the idea to create a nested list where every list item is another list that contains the player information, i.e. player name and score, for example:

players = [['Player 1', 0], ['Player 2', 0]]

In this example, there are two players. Player 1 and Player 2 with each a current score of 0. Here an example code:

import random
players = [['Player 1', 0], ['Player 2', 0]]

while players[0][1] < 100 and players[1][1] < 100:
    chances = [0, 1]
    for i in range(0, len(players)):
        player = players[i]
        score = random.choice(chances)
        if score == 1:
            player[1] += 1
        if player[1] == 100:
            winner = player[0]

print('Congrats {0}, you have won the game'.format(winner))

chances is whatever game they are playing, if a player gets a 0 nothing happens, if he gets a 1, his score increases by 1. Whoever reaches 100 first wins the game.

If there was now a third, fourth or fifth player, I would have to adjust the WHILE loop in the code acoordingly:

players = [['Player 1', 0], ['Player 2', 0], ['Player 3', 0]

or

players = [['Player 1', 0], ['Player 2', 0], ['Player 3', 0], ['Player 4', 0]

and so forth.

Is there a dynamic way to do that where I do not need to have a fixed number of players or cause an IndexError exception?

1

There are 1 best solutions below

0
John Gordon On

You can use the all() function together with a generator expression:

while all(player[1] < 100 for player in players)

If all players have a score less than 100, all() will return true, otherwise if any player has 100 or more, all() will return false.