Beginner question: returning a boolean value from a function in Python

前端 未结 2 690
迷失自我
迷失自我 2021-02-19 13:17

I\'m trying to get this rock paper scissors game to either return a Boolean value, as in set player_wins to True or False, depending on if the player wins, or to re

相关标签:
2条回答
  • 2021-02-19 13:53

    Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

    def rps():
        # Code to determine if player wins
        if player_wins:
            return True
    
        return False
    

    Then, just assign a value to the variable outside this function like so:

    player_wins = rps()
    

    It will be assigned the return value (either True or False) of the function you just called.


    After the comments, I decided to add that idiomatically, this would be better expressed thus:

     def rps(): 
         # Code to determine if player wins, assigning a boolean value (True or False)
         # to the variable player_wins.
    
         return player_wins
    
     pw = rps()
    

    This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

    0 讨论(0)
  • 2021-02-19 14:00

    Have your tried using the 'return' keyword?

    def rps():
        return True
    
    0 讨论(0)
提交回复
热议问题