我如何 return 在 Python 中定义局部变量?

How can I return with a local variable in definition in Python?

我正在尝试创建一个玩棍子游戏的简单 AI 程序。问题是我想从总棒数中减去选择的棒。这个简单的代码显示了一些错误,例如不存在的值。我无法为我的值分配返回值。还有其他方法可以用函数减去值吗?

import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)

# First player move

def robot(stick):
    y = stick % 4
    if y==0:
        y=randint(1,3)
    mov=int(y)
    print('machine chose:', mov)
    total = stick-mov
    return total

def human(stick2):
    mov2= int(input('your turn:'))
    print('human chose:', mov2)
    total = stick2-mov2
    return total

players= {
    '1': robot,
    '2': human

        }

number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')

player1=players[number1]
player2=players[number2]
print(player1, player2)

print('the game begins')

while True:
   player1(int(msg))
   if msg == 0: break

   print('remained sticks:', msg)
   player2(int(msg))
   print('remained sticks:', msg)
   if msg == 0: break

return 当然有用;它 returns 一个值。但是在您的代码中您没有捕获该值,它会立即被丢弃。

确实不清楚你想要什么,但也许你想要这样的东西:

msg = player1(int(msg))

你的播放器是参考函数:

players= {
    '1': robot,
    '2': human
        }

稍后您称它们为 player1player2:

player1=players[number1]
player2=players[number2]

但是当您使用这些函数时 您不会对 return 值做任何事情:

player1(int(msg))
...
player2(int(msg))

所以那些函数 return 有些东西,但是你忽略了这个值。您需要打印该 return 值或将其分配给一个变量,以便稍后可以对该值执行某些操作。

因为你的 return 值被称为 total 也许你想要:

total = player1(int(msg))
print('new total:', total)