1

Can we write the following code in one line, when a function switch the current player another one?

    def switch_user(self,current):
       if self.current == 'Player-1':
              self.current = 'Player-2'
      elif self.current == 'Player-2':
           self.current = 'Player-1'
    return
  • 1
    See [Replacements for switch statement in Python?](http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – e0k Dec 17 '16 at 06:57
  • 2
    @e0k While that would work, it sounds like this question isn't really asking about equivalents for a `switch` statement - the use of the word "switch" is coincidental. It seems to be asking how to concisely toggle between two values. – David Z Dec 17 '16 at 07:12
  • @DavidZ Good point. The code looks similar to a switch statement because it is making multiple comparisons against the same value. That must have distracted me. The word "switch" in the question only refers to switching players. – e0k Dec 17 '16 at 07:22

2 Answers2

2
self.current = 'Player-2' if self.current == 'Player-1' else 'Player-1'
Amber
  • 507,862
  • 82
  • 626
  • 550
1

To make things expandable to multiple players I'd use cycle from the itertools standard library https://docs.python.org/2/library/itertools.html#itertools.cycle

from itertools import cycle      

players_cycle = cycle(['Player-1', 'Player-2'])

current = players_cycle()

This way you are able add a third player or make the player objects more complex over time Without having to redo the switch function.

Nath
  • 748
  • 4
  • 16