Python Forum
Better way to write this function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Better way to write this function
#1
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.
Reply
#2
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]
SephMon likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  write new function or change the old one to work "smartter? korenron 3 1,991 Aug-09-2021, 10:36 AM
Last Post: jamesaarr
  How can I write a function with three parameters? MehmetAliKarabulut 1 2,437 Mar-04-2021, 10:47 PM
Last Post: Larz60+
  How to write a code with İF function? Aycaaxx 1 1,852 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  Print/write to file function tpolim008 4 2,801 Apr-01-2020, 07:59 PM
Last Post: tpolim008
  How to write test cases for a init function by Unit test in python? binhduonggttn 2 3,133 Feb-24-2020, 12:06 PM
Last Post: Larz60+
  write an integer to file using a function xvkxvo 4 3,213 Dec-10-2019, 11:27 PM
Last Post: xvkxvo
  how can I write my function output on CSV file go127a 13 5,551 May-05-2019, 01:55 PM
Last Post: go127a
  Use the write function manonB 2 2,543 Apr-17-2019, 05:55 AM
Last Post: manonB
  Help trying to write a function Rochense 3 4,278 Apr-12-2019, 02:34 PM
Last Post: Gribouillis
  'function' object has no attribute 'write' paramiko lateublegende 1 5,412 Feb-12-2019, 09:03 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020