python run 3 while loops indefinitely

82 views Asked by At

I am trying to make the 3 while loops run indefinitely, but right now when the while player == 2 loop ends, the variable player = 0 due to the function, but the loop does not go back to the first while loop.

def nextplayer():
    global player
    if player == 0:
        player = 1
    elif player ==1:
        player = 2
    elif player == 2:
        player = 0

while player == 0:
    print('Player 1 turn')
    spinwheel()
    nextplayer()

while player == 1:
    print('Player 2 turn')
    spinwheel()
    nextplayer()

while player == 2:
    print('Player 3 turn')
    spinwheel()
    nextplayer()
1

There are 1 answers

0
chepner On

This would be much simpler with itertools.cycle:

from itertools import cycle


for player in cycle([0,1,2]):
    print(f'Player {player} turn')
    spinwheel()

No need to call a function nextplayer that mutates a global variable.