【发布时间】: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