![]() |
Better way to write this function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Better way to write this function (/thread-39379.html) |
Better way to write this function - SephMon - Feb-08-2023 Hello I have created a rock paper scissors game, it works fine but one function is very long and I was wondering if maybe there was a better way to write it def check_who_won(self): self.print_out_computer_choice() if self.player_choice == 0 and self.computer_choice == 0: self.player_score +=1 self.print_score() self.check_score(self.player_score) elif self.computer_choice == 0 and self.player_choice == 2: self.computer_score +=1 self.print_score() self.check_score(self.computer_score) elif self.computer_choice > self.player_choice: self.computer_score +=1 self.print_score() self.check_score(self.computer_score) elif self.player_choice > self.computer_choice: self.player_score +=1 self.print_score() self.check_score(self.player_score) elif self.computer_choice == self.player_choice: print("DRAW!")this function checks if computer or player won, it displays score and updates score but its very long and I'm just wondering if that function could be condensed , thanks for reading. RE: Better way to write this function - Gribouillis - Feb-08-2023 You could try code like winner = ["nobody", "computer", "player"][(self.computer_choice - self.player_choice) % 3]It can be made even shorter by using negative indexes in Python list (still assuming computer_choice and player_choice are in (0, 1, 2)) winner = ["nobody", "computer", "player"][self.computer_choice - self.player_choice] |