我需要找到一个用户输入的数字列表的平均值和一些不工作

2024-04-26 12:58:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须做一个程序,用户输入几个数字,并输入一个特定的数字,以停止输入过程,并收到一个平均值。它应该检测到用户专门输入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时,它会继续询问数字。你知道吗


Tags: the用户程序inputreturn过程def数字
3条回答

在python3.xx中input()将输入读取为str,因为1234567 != "1234567"所以它与整数1234567不匹配

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

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

首先,您需要将输入从str解析到int。第二,尽管我不同意这种方法,但您应该从sum中删除1234567,并将list元素减少1以得到正确的结果。例如:

def averages():
    def Average(lst):
        try:
            return (sum(lst)-1234567)/(len(lst)-1)
        except ZeroDivisionError:
            return 0
    nums=[]
    while 1234567 not in nums:
        nums.append(int(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)

averages()

您正在尝试的代码有两个问题,下面将修复这两个问题

def averages():
    def Average(lst):
        try:
            return sum(lst)/len(lst)
        except ZeroDivisionError:
            return 0
    nums=[]
    list =[1,2,3,4,5,6,7]
    while 1==1:
        input_num = (int(input("Please input numbers and type 1234567 when you wish to find the average if the numbers inputted")))
        if input_num in list:
            nums.append(input_num)
        else:
            break

    mean=Average(nums)
    print(nums)
    print(mean)

if __name__ == '__main__':
    averages()

相关问题 更多 >