【问题标题】:ValueError: invalid literal for int() with base 10 and occasion EOL while scanning string literalValueError: int() 的无效文字,以 10 为底,并且在扫描字符串文字时出现 EOL
【发布时间】:2011-12-01 03:27:33
【问题描述】:

我是一个 python 新手,我正在尝试创建和定义一组函数来计算列表中一组数字的中值模式和平均值。我还尝试包含一个 main 函数,该函数使用给定列表测试所有 3 个函数。在过去的 3 天里,我一直在出错,我在谷歌上找不到任何有用的解决方案。我最近的错误是

ValueError: invalid literal for int() with base 10. 

我做错了什么?我的脚本中是否还有其他我可能忽略的错误?

"""
File: stats.py
"""
#Prints median of a set of numbers in a list
numList = int(input("Enter a list of numbers"))

def median(list):
    numList = []
numList.sort()
middle = len(numList)//2
if len(numList) % 2 == 1:
    print(numList[middle])
print((numList[middle] + numList[middle - 1])/2)
if numList == []:
    print (0)

#Prints mode of a set of numbers in a list
def mode(list):
    numList = []
    for repeat in numList:
        number = nums.get(repeat,none)
    if number == none:
        nums[repeat] = 1
        nums[repeat] = number + 1
        theMaximum = max(nums.values())
        for repeat in nums:
            if nums[repeat] == theMaximum:
                print (repeat)
                if numList == []:
                    print (0)

#Prints average of a set of numbers in a list
def mean(list):
    sum = 0
    for number in numList:
        sum += number
        print (sum)/len(numList)
        if numList == []:
            print (0)

#The main function for this script
def main():
    numList = [2,6,18,42,90,18,9,15,26,18,82]
    result = mean[2,6,18,42,90,18,9,15,26,18,82]
    print("The mean of" , [2,6,18,42,90,18,9,15,26,18,82], "is", result)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    错误在这里:

    numList = int(input("Enter a list of numbers"))
    

    如果是数字,您输入一个列表。然后您使用int() 方法尝试将这个列表 转换为一个整数。

    这显然失败了。 “1,2,3,4,5”不是整数,是五个整数,需要分别转换。

    有多种方法可以做到这一点,.split(',') 是一种方法,使用外观并逐个询问整数是另一种方法。

    【讨论】:

    • 还有更多错误。修复后由于result = mean[2,6,18,42,90,18,9,15,26,18,82],它不应该运行
    • @joaquin:哦,当然还有更多错误,但一次只有一件事。我不会为他编写他的代码,他不会那样学习。 :-) 他的问题是他没有测试任何代码就编写了代码,而且它不起作用。代码应该逐行编写。
    猜你喜欢
    • 2018-09-09
    • 2020-01-04
    • 2010-12-22
    • 2011-07-07
    • 2019-10-14
    • 2022-05-19
    相关资源
    最近更新 更多