Python 3,将数据从一个函数传递到另一个函数

时间:2013-11-13 19:27:46

标签: python function python-3.x

def main():
    uInput()
    calc()
def uInput():
    value1 = int(input('Please put in the first number'))
    value2 = int(input('Please put in your second number'))
    return value1
    return value2
def calc(value1,value2):    
    finalNumber = value1 + value2
    print (finalNumber)
main()

我正在搞乱python,我正在尝试制作一个简单的计算器程序。我正在尝试将输入值从uInput模块传递给calc模块。它一直在说缺少两个必要的位置参数。你能只将一个变量从模块传递到另一个模块吗?

4 个答案:

答案 0 :(得分:4)

函数在遇到的第一个return语句处退出,因此永远不会到达return value2。要返回多个值,请使用tuple

return value1, value2     #returns a tuple

uInput()的返回值分配给main中的变量:

val1, val2 = uInput()  #Assign using sequence unpacking 

将这些变量传递给calc

calc(val1, val2)       

更正版本:

def main():
    val1, val2 = uInput()
    calc(val1, val2)

def uInput():
    value1 = int(input('Please put in the first number'))
    value2 = int(input('Please put in your second number'))
    return value1, value2

def calc(value1,value2):    
    finalNumber = value1 + value2
    print (finalNumber)
main()

答案 1 :(得分:1)

基本上,一个函数只能返回一次。当你使用return语句时,流程就会“返回”,所以代码中的第二个返回是无法访问的。

但是,在python中,您可以将多个值作为“元组”返回:

return value1,value2

答案 2 :(得分:1)

您可以从任何函数一次返回两个东西,但是您只能使用一个return语句。通过使用return x, y,它会返回一个元组(x, y),您可以在主函数中使用它。

def uInput():
    value1 = int(input('Please put in the first number'))
    value2 = int(input('Please put in your second number'))
    return value1, value2 # this returns a tuple

def main():
    val1, val2 = uInput() # unpack the tuple values into two variables
    calc(val1, val2)

答案 3 :(得分:0)

def uInput():
    value1 = int(input('Please put in the first number'))
    value2 = int(input('Please put in your second number'))
    return value1, value2             # this returns a tuple

def calc(value1,value2):    
    finalNumber = value1 + value2
    print (finalNumber)

def main():
    val1, val2 = uInput()   # unpack the tuple values into two variables
    calc(val1, val2)     # this is one method which uses two temporary variables

    # ALternatively you can use python's argument unpacker(*) to unpack the tuple in the function call itself without using any temporary variables.

    calc(*uInput())

有关详细信息,请查看http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists