初学者问题:从Python中的函数返回一个布尔值

时间:2010-11-12 15:04:39

标签: python function boolean

我正在尝试让这个石头剪刀游戏返回一个布尔值,如在集合player_wins中为True或False,具体取决于玩家是否获胜,还是完全重构此代码以便它不使用while循环。 我是来自世界各地的系统管理员,所以如果这是以错误的方式写的,请保持温柔。 我已经尝试了一些东西,我理解TIMTOWTDI,并且只是喜欢一些输入。

感谢。

import random

global player_wins
player_wins=None

def rps():

    player_score = 0
    cpu_score = 0

    while player_score < 3 and cpu_score < 3:

        WEAPONS = 'Rock', 'Paper', 'Scissors'

        for i in range(0, 3):
          print "%d %s" % (i + 1, WEAPONS[i])

        player = int(input ("Choose from 1-3: ")) - 1
        cpu = random.choice(range(0, 3))

        print "%s vs %s" % (WEAPONS[player], WEAPONS[cpu])
        if cpu != player:
          if (player - cpu) % 3 < (cpu - player) % 3:
            player_score += 1
            print "Player wins %d games\n" % player_score
          else:
            cpu_score += 1
            print "CPU wins %d games\n" % cpu_score
        else:
          print "tie!\n"
rps()

我正在尝试做这样的事情:

   print "%s vs %s" % (WEAPONS[player], WEAPONS[cpu])
    if cpu != player:
      if (player - cpu) % 3 < (cpu - player) % 3:
        player_score += 1
        print "Player wins %d games\n" % player_score
        if player_score == 3:
            return player_wins==True
      else:
        cpu_score += 1
        print "CPU wins %d games\n" % cpu_score
        if cpu_score == 3:
            return player_wins==False
    else:
      print "tie!\n"

2 个答案:

答案 0 :(得分:31)

忽略重构问题,您需要了解函数和返回值。你根本不需要全局。永远。你可以这样做:

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

    return False

然后,只需为此函数外的变量赋值,如下所示:

player_wins = rps()

将为您刚调用的函数分配返回值(True或False)。


在评论之后,我决定以惯用方式添加,这样可以更好地表达:

 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()

这将player_wins(函数内部)的布尔值赋给函数外的pw变量。

答案 1 :(得分:2)

您是否尝试过使用'return'关键字?

def rps():
    return True