def data():
num_1 = int(input("Please select a number\n"))
num_2 = int(input("Please select a number\n"))
data()
def main(num_1,num_2) :
print(num_1+num_2)
main(num_1,num_2)
我是Python的新手。我应该怎么做才能让我的main
函数访问data
函数?
答案 0 :(得分:0)
在python中,可以使用return
语句将信息从一个函数移到另一个函数。然后,当您调用函数时,该值将传回:
value = data()
# Now value is the returned value.
因此,用于移动值的完整数据功能是:
def data():
num_1 = int(input("Please select a number\n"))
num_2 = int(input("Please select a number\n"))
return num_1, num_2 # Really, you are returning a tuple (num1, num2).
因此,可以通过调用以下方式接收该值:
num_1, num_2 = data() # This is a special syntax that python supports called unpacking.
# Doing something like this would also work:
values = data()
num_1 = values[0] # Get first value of the tuple that was returned.
num_2 = values[1]
此外,python中的标准约定是在运行代码之前声明所有函数。您不必这样做,但是如果在声明函数之前尝试调用该函数,则会出错。
因此,考虑到所有这些,您的最终代码应该是:
# Declare the data function.
def data():
num_1 = int(input("Please select a number\n"))
num_2 = int(input("Please select a number\n"))
return num_1, num_2
# Declare the main function (not run yet).
def main(num_1, num_2):
print(num_1 + num_2)
num_1, num_2 = data() # Call data and save the output.
main(num_1, num_2) # Now call main with the numbers.
另外,对于您的代码,您可能想在data()
中调用main()
,因为所有代码都应在main()
函数中。因此,考虑到这一点,您的代码将如下所示:
# Declare the data function.
def data():
num_1 = int(input("Please select a number\n"))
num_2 = int(input("Please select a number\n"))
return num_1, num_2
# Declare the main function (not run yet).
def main():
num_1, num_2 = data() # Call data inside of main. These variables are only visible in main()
print(num_1 + num_2)
main() # Now call main.
有些资料可能会有所帮助。
答案 1 :(得分:0)
def data():
num_1 = int(input("Please select a number\n"))
num_2 = int(input("Please select a number\n"))
return (num_1, num_2)
def main(num_1,num_2) :
print(num_1+num_2)
nums = data()
main(nums[0], nums[1])
您的函数data()应该返回其数据,以便将其传递给另一个函数。通过调用data(),您应该将结果存储在变量中,然后将其传递给main(num_1,num_2)函数。您甚至可以更简单地将args传递给main:main(*nums)
。所以:
def data():
num_1 = int(input("Please select a number\n"))
num_2 = int(input("Please select a number\n"))
return (num_1, num_2)
def main(num_1,num_2) :
print(num_1+num_2)
nums = data()
main(*nums)