python - 初学者问题: returning a boolean value from a function in Python

标签 python function boolean

我试图让这个剪刀石头布游戏返回一个 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"

最佳答案

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

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 的 boolean 值(在函数内)分配给函数外的 pw 变量。

关于python - 初学者问题: returning a boolean value from a function in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4165933/

相关文章:

python - 如何区分类、函数和方法

c# - 从 C++ 到 C# 的 bool 指针

python - 将 2x2 DataFrame 整理成 4x1 系列 (Pandas)

python - 如何在 Tkinter 中将变量传递给 stringvar 并在标题中设置自己的位图?

Python Actor 模型 : thespian vs pykka

python - 尝试/排除和决策

C++使用仿函数将函数传递给函数

javascript - 创建一个类似 "$"对象的 jQuery

java - 我如何在 Java 中返回 boolean 值?

javascript - 同时检查来自多个数组的 boolean 值,没有多个 if 语句