调用函数时如何在函数中定义变量?
Posted
技术标签:
【中文标题】调用函数时如何在函数中定义变量?【英文标题】:How to define a variable in a function when calling the function? 【发布时间】:2021-12-21 20:05:37 【问题描述】:当我运行我的代码时,我得到“NameError: name ‘mean’ is not defined”。当我尝试调用我的函数“calculateVariance(mean, nums)”时出现此错误。我似乎无法弄清楚如何在不必更改“calculateVariance(mean, nums)”函数的情况下定义“均值”.. 如果这有意义..
代码如下:
import math
import matplotlib.pyplot as plt
def readFile(file_name):
with open('data_1.txt', 'r') as DataOne:
nums = DataOne.read()
print(nums)
return nums
def calculateMean(nums):
sumOfNums = 0
for i in range(len(nums)):
sumOfNums += i
mean = sumOfNums//len(nums)
print("The mean is : ", mean)
return mean
def calculateVariance(mean, nums):
squaredDifferences = 0
for number in nums:
difference =mean - number
squaredDiff = difference ** 2
squaredDifferences += squaredDiff
variance = squaredDifferences // (len(nums)-1)
print(" The variance is : ", variance)
return variance
def calculateSD(variance):
square_root = math.sqrt(number)
StandDev = square_root(variance)
print("Standard Deviation is : ", StandDev)
return StandDev
def showHistogram(nums):
num_bins = 10
plt.hist(listOfNums, num_bins)
plt.show()
nums = readFile('data_1.txt')
calculateMean(nums)
calculateVariance(mean, nums)
calculateSD(variance)
【问题讨论】:
请始终发布带有完整回溯的整个错误消息。您的缩进也不正确。这是复制/粘贴错误还是您的实际代码?return
语句应该缩进,以便它们属于函数。
如果您在函数calculateMean()
中定义mean
,它将仅对该函数是本地的。这意味着它不能在函数之外使用。假设缩进问题只是一个拼写错误,您应该使用来自calculateMean()
的返回值——类似于mean = calculateMean(nums)
。
仅供参考,如果您使用 pandas
包,这些只是单行调用:nums.mean()
、nums.var()
【参考方案1】:
当您调用返回mean
的函数时,您实际上并没有保存它。因此在调用其他函数时不能使用它。
尝试将其保存为 mean_result
或类似名称以供以后使用(避免命名冲突)。
【讨论】:
【参考方案2】:您应该将来自函数calculateMean(nums)
的mean
结果存储在一个变量中。您还需要为其他功能执行此操作。
import math
import matplotlib.pyplot as plt
def readFile(file_name):
with open('data_1.txt', 'r') as DataOne:
nums = DataOne.readlines()
print(nums)
return nums
def calculateMean(nums):
sumOfNums = 0
for i in range(len(nums)):
sumOfNums += i
mean = sumOfNums//len(nums)
print("The mean is : ", mean)
return mean
def calculateVariance(mean, nums):
squaredDifferences = 0
for number in nums:
if number != '':
difference = mean - int(number.replace('\n', ''))
squaredDiff = difference ** 2
squaredDifferences += squaredDiff
variance = squaredDifferences // (len(nums)-1)
print(" The variance is : ", variance)
return variance
def calculateSD(variance):
square_root = math.sqrt(number)
StandDev = math.sqrt(variance)
print("Standard Deviation is : ", StandDev)
return StandDev
def showHistogram(nums):
num_bins = 10
plt.hist(listOfNums, num_bins)
plt.show()
nums = readFile('data_1.txt')
mean = calculateMean(nums)
variance = calculateVariance(mean, nums)
stdev = calculateSD(variance)
【讨论】:
当我这样做时,我在mean - number
更改为mean - int(number.replace('\n', ''))
txt阅读器的每一行似乎都有换行符或\n
当我这样做时,我得到“文件“N:\Fall 2021\DataScience Intro to Python\Lab 12\SDandHistogram.py”,第 37 行,在 calculateVariance 差异 = mean - int(numbers.replace ('\n', '')) ValueError: int() 基数为 10 的无效文字:'' "以上是关于调用函数时如何在函数中定义变量?的主要内容,如果未能解决你的问题,请参考以下文章