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
3
  • 1
    See Replacements for switch statement in Python? Commented Dec 17, 2016 at 6: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. Commented Dec 17, 2016 at 7: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. Commented Dec 17, 2016 at 7:22

2 Answers 2

2
self.current = 'Player-2' if self.current == 'Player-1' else 'Player-1'
Sign up to request clarification or add additional context in comments.

3 Comments

shouldn't that be current == 'Player-1' instead of self.current == 'Player-1'?
@MohammadYusufGhazi current would make more sense (otherwise you're not using the argument), but then the example in the question is also incorrect.
I am using self because 'current' is a global variable, with self.current it becomes local.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.