微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Python 中调用函数到新函数

如何解决在 Python 中调用函数到新函数

我已经尝试了几种不同的方法,我对 Python 还是很陌生,所以放轻松。我正在尝试执行一个脚本,用户可以选择从纯文本文件导入列表,或手动输入列表,脚本将返回数据的中位数和众数。

我遇到的问题是我的中位数和众数函数无法识别对原始数据的引用,并且主函数无法从它们各自的函数中识别中位数和众数。

我想可以肯定地说我没有正确调用这些函数,但坦率地说,我只是不知道如何调用。非常感谢这里的任何帮助。

def choice():
    ##Choose user input type
    start = input("Please select your input method by typing 'file' or 'manual' in all lower-case letters: ")
    # Import File Type
    userData = []
    if start == "file":
        fileName = input("Please enter the file name with the file's extension,e.g. ' numbers.txt': ")
        userData = open(fileName).read().splitlines()
        return userData
        userData.close()
    # Manual Entry Type
    elif start == "manual":
        while True:
            data = float(input("Please enter your manual data one item at a time,press enter twice to continue: "))
            if data == "":
                break
            userData = data
            return userData
    # Error
    else:
        print("You have entered incorrectly,please restart program")


def median(medianData):
    numbers = []
    for line in (choice(userData)):
        listData = line.split()
        for word in listData:
            numbers.append(float(word))

    # Sort the list and print the number at its midpoint
    numbers.sort()
    midpoint = len(numbers) // 2
    print("The median is",end=" ")
    if len(numbers) % 2 == 1:
        medianData = (numbers[midpoint])
        return medianData
    else:
        medianData = ((numbers[midpoint] + numbers[midpoint - 1]) / 2)
        return medianData


def mode(modeData):
    words = []
    for line in (choice(userData)):
        wordsInLine = line.split()
        for word in wordsInLine:
            words.append(word.upper())
    theDictionary = {}
    for word in words:
        number = theDictionary.get(word,None)
        if number == None:
            theDictionary[word] = 1
        else:
            theDictionary[word] = number + 1


    theMaximum = max(theDictionary.values())
    for key in theDictionary:
        if theDictionary[key] == theMaximum:
            theMaximum = modeData
            break
        return modeData

def main():
    print("The median is",(median(medianData)))
    print("The mode is",(mode(modeData)))

解决方法

欢迎!我认为您需要更多地了解函数的工作原理。 定义函数时的参数是一个“虚拟”局部变量,其名称仅在函数定义中重要。您需要为其提供一个变量或常量,其名称在您使用它的地方有意义。这是对数学函数的一个很好的类比,你可能在学校里学过。 (请注意,这些点不是 Python 特有的,尽管详细的语法是。)

因此,当您有 def median(medianData) 时,您需要在函数定义中使用 medianData,而不是 userData,并且当您调用 {{1} } 您必须确保 median(somevar) 在程序中的那个点具有值。

举一个更简单的例子:

somevar

你会如何使用它?您可以将其放在代码中的某个位置:

def doubleMyVariable(x):
   return 2*x

应该打印出print(doubleMyVariable(3))

或者这个:

6

这将打印 z = 12 y = doubleMyVariable(z) print(y)

你甚至可以这样做

12

这会将 z = 36 x = doubleMyVariable(z) 分配给变量 72。但是你看到我在那里如何使用 x 了吗?与函数定义中的x无关。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。