Karyon Trotters
Karyon Trotters

Reputation: 13

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!

Upvotes: 0

Views: 1876

Answers (4)

quentin
quentin

Reputation: 1

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

Upvotes: 0

Buddy Bob
Buddy Bob

Reputation: 5889

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

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54718

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) )

Upvotes: 0

Woodford
Woodford

Reputation: 4449

>>> 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
...

Upvotes: 5

Related Questions