我正在制作一个用户输入一些数字的程序,然后他们可以选择计算数字的均值,中位数,模式或范围。
这是我的代码。
import statistics
def number():
yn = 'y'
while yn == 'y':
x = input("Enter a number.")
numbers = []
numbers.append(x)
yn = input('Enter another one? y/n')
if yn == 'n':
break
return numbers
def findaverage(x):
x = sum(x)-len(x)
print(x)
def findrange(x):
x = max(x) - min(x)
print(x)
def findmode(x):
x = statistics.mode(x)
print(x)
def findmedian(x):
x = statistics.median(x)
print(x)
def main():
numbers = number()
x = ''
while x != "1" or x != "2" or x != "3" or x != "4":
x = str(input("What would you like to do?\n1.Average\n2.Range\n3.Mode\n4.Median"))
if x == "1":
findaverage(numbers)
elif x == "2":
findrange(numbers)
elif x == "3":
findmode(numbers)
elif x == "4":
findmedian(numbers)
main()
当我运行程序时,它给了我以下追溯:
Enter a number.2
Enter another one? y/ny
Enter a number.4
Enter another one? y/ny
Enter a number.5
Enter another one? y/nn
What would you like to do?
1.Average
2.Range
3.Mode
4.Median1
File "C:\file.py", line 45, in <module>
File , line 45, in <module>
main()
main()
File , line 36, in main
File , line 36, in main
findaverage(numbers)
findaverage(numbers)
File , line 19, in findaverage
x = sum(x)-len(x)
TypeError: 'NoneType' object is not iterable
我不确定导致此问题的原因。
请帮助,谢谢!
答案 0 :(得分:3)
问题是:
numbers = []
)。将其移出循环。 break
语句。input
获取字符串,但您的函数需要整数。制作x = int(input("Enter a number."))
。答案 1 :(得分:2)
问题是并非所有通过number()
的代码路径都有明确的return
语句。如果没有明确的返回,则隐式返回None
。