首页 > 解决方案 > 在后面的函数中使用返回值

问题描述

假设我想调用一个函数来进行一些计算,但我也想在以后的函数中使用该计算值。当我返回第一个函数的值时,我可以不只是将它发送到我的下一个函数吗?这是我正在谈论的一个例子:

def add(x,y):
  addition = x + y
  return addition

def square(a):
  result = a * a
  return result

sum = add(1,4)
product = square(addition)

如果我调用 add 函数,它将返回 5 作为加法结果。但是我想在下一个函数中使用那个数字 5,我可以将它发送到下一个函数,如图所示吗?在我正在处理的主程序中,它不是这样工作的。

编辑:这是我实际正在处理的代码示例,可以更好地了解问题所在。问题是当我将平均值发送到 calculateStdDev 函数时。

#import libraries to be used
import time
import StatisticsCalculations

#global variables
mean = 0
stdDev = 0

#get file from user
fileChoice = input("Enter the .csv file name: ") 
inputFile = open(fileChoice)

headers = inputFile.readline().strip('\n').split(',') #create headers for columns and strips unnecessary characters

#create a list with header-number of lists in it
dataColumns = []
for i in headers:
  dataColumns.append([]) #fills inital list with as many empty lists as there are columns

#counts how many rows there are and adds a column of data into each empty list
rowCount = 0
for row in inputFile:
  rowCount = rowCount + 1
  comps = row.strip().split(',') #components of data
  for j in range(len(comps)):
    dataColumns[j].append(float(comps[j])) #appends the jth entry into the jth column, separating data into categories

k = 0
for entry in dataColumns:
  print("{:>11}".format(headers[k]),"|", "{:>10.2f}".format(StatisticsCalculations.findMax(dataColumns[k])),"|", 
    "{:>10.2f}".format(StatisticsCalculations.findMin(dataColumns[k])),"|","{:>10.2f}".format(StatisticsCalculations.calculateMean(dataColumns[k], rowCount)),"|","{:>10.2f}".format()) #format each data entry to be right aligned and be correctly spaced in its column
#prining break line for each row
  k = k + 1 #counting until dataColumns is exhausted

inputFile.close()

和 StatisticsCalculations 模块:

import math

def calculateMean(data, rowCount):
  sumForMean = 0
  for entry in data:
    sumForMean = sumForMean + entry
    mean = sumForMean/rowCount

  return mean

def calculateStdDev(data, mean, rowCount, entry):
  stdDevSum = 0 
  for x in data: 
    stdDevSum = float(stdDevSum) + ((float(entry[x]) - mean)** 2) #getting sum of squared difference to be used in std dev formula
  stdDev = math.sqrt(stdDevSum / rowCount) #using the stdDevSum for the remaining parts of std dev formula

  return stdDev


def findMin(data):
  lowestNum = 1000
  for component in data:
    if component < lowestNum:
      lowestNum = component

  return lowestNum

def findMax(data):
  highestNum = -1
  for number in data:
    if number > highestNum:
      highestNum = number

  return highestNum

标签: pythonfunctionreturn-value

解决方案


首先,sum是一个保留字,你不应该把它用作变量。

你可以这样做:

def add(x,y):
  addition = x + y
  return addition

def square(a):
  result = a * a
  return result

s = add(1, 4)
product = square(s)

或直接:

product = square(add(1, 4))

推荐阅读