【问题标题】:How to get two variables from the previous function in python? [duplicate]如何从python中的前一个函数中获取两个变量? [复制]
【发布时间】:2014-06-28 12:37:47
【问题描述】:

我对 python 很陌生,所以我还在学习一些东西。但我正在编写这段代码,我需要知道如何从“getHumanMove”函数中获取 x 和 y 变量,以便可以在“getPiles”函数中使用它

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)

【问题讨论】:

    标签: python


    【解决方案1】:

    当一个函数返回两个值时,你可以这样做

    value1, value2 = some_function(argument1, argument2, argument3, ...)
    

    将两个返回值存储在value1value2中。

    【讨论】:

      【解决方案2】:

      你可以使用tuple unpacking:

      move = getHumanMove(pile1, pile2)
      pile = getPiles(*move)
      

      或者单独获取每个变量,这样你也可以单独传递它们:

      move1, move2 = getHumanMove(pile1, pile2)
      pile = getPiles(move1, move2)
      

      【讨论】:

        【解决方案3】:

        你打电话给 getPiles 怎么样:

        pile = getPiles(pile1, pile2, move)
        

        然后在你的 getPiles 定义中:

        def getPiles(pile1, pile2, move):
            x, y = move
        

        【讨论】:

          【解决方案4】:

          假设这就是你的意思:

          x,y = getHumanMove(pile1, pile2)
          pile1, pile2 = getPiles(x, y)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-01-18
            • 1970-01-01
            • 1970-01-01
            • 2016-03-11
            • 1970-01-01
            • 2021-02-26
            • 2018-03-30
            • 1970-01-01
            相关资源
            最近更新 更多