pythonalternating

Is there any way to alternate between two values in python


Suppose I have a value say Player 1 and Player 2. Can I assign them to a single variable in such a way such that

print("%s choose this piece" %Player_value)

Expected output

Player 1 choose this value
Player 2 choose this value

How can this be done!

Please help!


Solution

  • >>> import itertools
    >>> player = itertools.cycle(['Player 1', 'Player 2'])
    >>> print("%s choose this piece" % next(player))
    Player 1 choose this piece
    >>> print("%s choose this piece" % next(player))
    Player 2 choose this piece
    >>> print("%s choose this piece" % next(player))
    Player 1 choose this piece
    ...