0
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

4 回答 4

6

函数在遇到的第一个 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()
于 2013-11-13T19:32:35.700 回答
1

基本上,一个函数只能返回一次。当您使用 return 语句时,流程实际上是“返回”,因此代码中的第二个返回是无法访问的。

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

return value1,value2
于 2013-11-13T19:30:36.623 回答
1

您可以从任何函数一次返回两件事,但您只能使用一个 return 语句。通过使用return x, y它返回一个 tuple (x, y),你可以在你的 main 函数中使用它。

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)
于 2013-11-13T19:31:34.613 回答
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

于 2017-10-13T11:55:03.523 回答