简体   繁体   English

你如何从python中的函数返回多个变量

[英]How do you return multiple variables from a function in python

I am creating a game that is played in the terminal and I wanted to reduce the amount of repetitive code by using functions eg我正在创建一个在终端中播放的游戏,我想通过使用函数来减少重复代码的数量,例如

def p1_end_turn(p1_turn, p2_turn):
    p1_turn = False
    p2_turn= True
    return p1_turn, p2_turn

however when running the program with the code p1_end_turn(p1_turn, p2_turn) the variable p1_turn and p2_turn have not been changed.然而,当使用代码p1_end_turn(p1_turn, p2_turn)运行程序时p1_end_turn(p1_turn, p2_turn)变量 p1_turn 和 p2_turn 没有改变。 How can I make this code properly return the variables (im using python3.9.1 and have checked that the function works properly)如何使此代码正确返回变量(我使用 python3.9.1 并检查该函数是否正常工作)

Returning a variable doesn't change the value of the variables.返回变量不会改变变量的值。 I think reading this page about variable scope and this page about immutable and mutable variables would be helpful.我认为阅读此页有关变量的作用域和 此页关于可变和不可变的变量将是有益的。
As it has mentioned in second link, boolean variables are immutable objects.正如它在第二个链接中提到的,布尔变量是不可变的对象。
If you really want to stick to your current code (which i highly recommend to first read links and decide what to do!), you can use something like this to change turns:如果你真的想坚持你当前的代码(我强烈建议先阅读链接并决定做什么!),你可以使用这样的东西来改变回合:

def change_trun(p1_turn, p2_turn):
    return not p1_turn, not p2_turn

# some codes
p1_turn, p2_turn = change_turn(p1_turn, p2_turn)

Last line is the key.最后一行是关键。 variables should update with returned values.变量应使用返回值更新。

Have a look at variable scopes (and possibly at mutable/immutable objects ).看看变量范围(可能还有可变/不可变对象)。 In short you only change p1_turn and p2_turn inside the function.简而言之,您只需更改函数内部的p1_turnp2_turn This means that outside the function the values stay the same.这意味着在函数之外,值保持不变。

Your variables in the function are not the same as the ones out of it.函数中的变量与函数中的变量不同。 Therefore you have to store the output in the variables you want.因此,您必须将输出存储在您想要的变量中。

def p1_end_turn(p1_turn, p2_turn):
    p1_turn = False
    p2_turn= True
    return p1_turn, p2_turn

P1_turn = True
P2_turn = True

P1_turn, P2_turn = p1_end_turn(P1_turn, P2_turn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM