【问题标题】:Calling function to new function in Python在 Python 中调用函数到新函数
【发布时间】:2021-06-16 14:10:59
【问题描述】:

我已经尝试了几种不同的方法,我对 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)))

【问题讨论】:

  • 能否包含回溯?此外,还有函数代码,但在它们之外没有任何东西在调用它们。当我运行此代码时,它不会返回错误
  • 您是 matlab 用户吗?您不需要将返回变量放在 Python 函数的参数列表中。将您的功能定义为例如def mode(): 另外,您使用参数调用了choice,但将其定义为不带任何参数。 choice() 是调用函数的正确方法
  • 您是否从命令行使用python myscript.py 调用您的脚本。如果是这样,您需要添加一个 dunder main,意思是:if __name__ == '__main__':
  • @Carcigenicate 它不会给出回溯错误,当我尝试运行它时会跳转到“进程以退出代码 0 完成”并且什么也不做。
  • 你似乎没有调用main(),这在 Python 中不是自动完成的。

标签: python function-call


【解决方案1】:

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

所以当您有def median(medianData) 时,您需要在函数定义中使用medianData,而不是userData,并且当您调用 median(somevar) 时,您必须确保@ 987654325@ 在你的程序中的那个点有一个值。

举个更简单的例子:

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 的吗?与函数定义中的x无关。

【讨论】:

  • 好的,既然我的选择函数随着 userData 变量的创建而终止,我该如何将该变量中的数据获取到另一个函数中。如果它是一个局部变量,我如何把它变成我可以在其他地方使用的东西?
  • 你的 choice 函数有 return UserData 所以在你的 main 你可以做类似myData=choice() 然后theMedianOfData=median(myData)
  • 这只是创建了一个循环,在该循环中我不断地在choice() 函数中重新输入输入。哈哈,我在这里有很多东西要学。
  • 您想从medianmode 函数之外调用choice。但我们的工作不是详细调试您的代码。相反,尝试学习“像计算机一样思考”,一次一行地逐步完成您的代码。
猜你喜欢
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
相关资源
最近更新 更多