How to get two variables from the previous function in python?
本问题已经有最佳答案,请猛点这里访问。
我对python很陌生,所以我还在学习一些东西。但是我正在编写这段代码,我需要知道如何从"gethumanmove"函数中获取x和y变量,以便在"getpires"函数中使用它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | def getHumanMove(x,y): finished = False while not finished: x=int(input("Which pile would you like to take from?(1 or 2)")) y=int(input("How many would you like from pile"+ str(x)+"?")) if pile1 and pile2<y: print("pile" +str(x)+" does not have that many chips. Try again.") elif y==0: print("You must take at least one chip. Try again.") else: print("That was a legal move. Thank You.") finished = True return x,y def getPiles(pile1, pile2): print("Here are the piles:") #################################Here is where I need to put the x, y variables pile1= pile1 pile2= pile2 if temp_x == 1: pile1= pile1- temp_y print("pile 1:", str(pile1)) print("pile 2:", str(pile2)) elif temp_x == 2: pile2= pile1- temp_y print("pile 1:", str(pile1)) print("pile 2:", str(pile2)) return pile1, pile2 ##############################Main############################## move= getHumanMove(pile1, pile2) pile= getPiles(pile1, pile2) |
打电话给GetPiles怎么样?
1 | pile = getPiles(pile1, pile2, move) |
然后在getpires定义中:
1 2 | def getPiles(pile1, pile2, move): x, y = move |
当函数返回两个值时,可以
1 | value1, value2 = some_function(argument1, argument2, argument3, ...) |
在
您可以使用tuple解包:
1 2 | move = getHumanMove(pile1, pile2) pile = getPiles(*move) |
或者分别获取每个变量,这样您也可以分别传递它们:
1 2 | move1, move2 = getHumanMove(pile1, pile2) pile = getPiles(move1, move2) |
假设这就是你的意思:
1 2 | x,y = getHumanMove(pile1, pile2) pile1, pile2 = getPiles(x, y) |