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

15 投票
3 回答
144327 浏览
提问于 2025-04-16 06:59

我正在尝试让这个石头剪刀布的游戏返回一个布尔值,也就是说,根据玩家是否获胜,把 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"

3 个回答

0
 def hit_cmpl(self):
        """To check if measured current is hitting the compliance. 
        if current hits the compliance, trip gets "1", otherwise '0'."""
        
        trip = self.keith2410.query(":sense:current:protection:tripped?")
        if trip:
            return True 

这段内容看起来是一个代码块,里面可能包含了一些编程相关的代码或示例。不过,由于没有具体的代码内容,我无法提供详细的解释。一般来说,代码块是用来展示程序代码的地方,帮助大家理解如何编写或使用某些功能。

如果你有具体的代码或者想要了解的内容,可以提供出来,我会更好地帮助你理解。

2

你试过用'return'这个关键词吗?

def rps():
    return True
37

忽略重构的问题,你需要理解函数和返回值的概念。其实你根本不需要全局变量。真的不需要。你可以这样做:

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 变量。

撰写回答