Is there any way to alternate between two values in python

Question:

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!

Asked By: Karyon Trotters

||

Answers:

>>> 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
...
Answered By: Woodford

There are a couple of good ways to do this kind of swap. An easy way is to use integers, 1 and 2. The swap then becomes:

    Player_value = 3 - Player_value

Another way is to have a list. This is overkill for two, but allows for more than two.

    Players = [1, 2]
    print("Player %d choose:" % Players[0] )
    Players.append( Players.pop(0) )
Answered By: Tim Roberts

Create a dictionary, and iterate through that. Keys are the player name and values are player values.

playerDict = {"Player1":"10","Player2":"20"}
for players in playerDict:print(f"{players} choose this {playerDict[players]}")

output

Player1 choose this 10
Player2 choose this 20
Answered By: Thavas Antonio

Code :

value=0
value = abs(value-1)
print(value)

Output :

0
1
0
1

if you want to use player A and B :

player=["A","B"]
value = 0
value = abs(value - 1)
print("player "+player[value])

Result :

player A
player B
player A
player B
Answered By: quentin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.