python返回函数值并退出函数,初学者的问题:从Python中的函数返回一个布尔值

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 refactor this code entirely so that it doesn't use a while loop.

I'm coming from the sysadmin side of the world, so please be gentle if this is written in the wrong style.

I have tried a few things, and I understand TIMTOWTDI, and would just like some input.

Thanks.

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

I'm trying to do something like this:

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"

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值