Skip to main content
 首页 » 编程设计

python之我需要找到用户输入数字列表的平均值,但有些东西不起作用

2025年05月04日14dflying

我必须编写一个程序,让用户输入多个数字并输入一个特定数字以停止输入过程并获得平均值。它应该检测到用户专门输入了 1234567,然后显示平均值,但它没有。我该如何解决这个问题?

def averages(): 
    def Average(lst):  
        try: 
            return sum(lst)/len(lst) 
        except ZeroDivisionError: 
            return 0 
    nums=[] 
    while 1234567 not in nums: 
        nums.append(input("Please input numbers and type 1234567 when you wish to find the average if the numbers inputted")) 
    mean=Average(nums) 
    print(nums) 
    print(mean) 

我希望它检测输入 1234567,然后输出所有已输入数字的平均值。但是当输入 1234567 时,它会继续询问数字。

请您参考如下方法:

在 Python 3.xx 中,input() 将输入读取为 str,这与 integer 1234567 不匹配,因为 1234567 != "1234567"

而是将输入类型强制转换为 int。例如:

int(input("Please input numbers and type 1234567 when you wish to find the average if the numbers inputted"))