【问题标题】:Average operation keeps giving "unsupported operand" error [duplicate]平均操作不断给出“不支持的操作数”错误[重复]
【发布时间】:2021-07-21 08:08:28
【问题描述】:

我正在尝试创建 5 个不同变量的平均值,每个变量都使用“int()”定义和建立,并且我不断收到“+: 'int' 和 'str' 不支持的操作数类型”错误.这是什么意思(简单来说)?我将“平均值”定义为列表的平均值。

number_list = [math, english, french, science, edtech]
average = sum(number_list)/5
int(average)
print("Your average mark is ",average,"!")

【问题讨论】:

  • 这意味着您正在尝试将int(整数)添加到str(字符串),这没有意义,例如2 + 'foo'

标签: python python-3.x


【解决方案1】:

听起来您列表中的项目之一是一个字符串。并且 Python 抱怨它无法将该字符串添加到 sum 函数的总数中。

【讨论】:

    【解决方案2】:

    很难说,因为我们看不到您定义的变量。错误只是从变量中的一个或多个字符串引发的,它们无法总结。

    如果您像代码中的平均值一样建立变量,它将无法正常工作。您可以通过repr()type()查看变量类型。

    # string with quote
    math = "1"
    int(math)
    print(repr(math))
    print(type(math))
    math = int(math)
    print(repr(math))
    print(type(math))
    # integer without quote
    english = 2
    print(repr(english))
    print(type(english))
    

    输出:

    '1'
    <class 'str'>
    1
    <class 'int'>
    2
    <class 'int'>
    

    如您所见,int(math) 不会将数学转换为整数,除非您通过 math = int(math) 执行此操作,或者您应该在第一次定义没有引号的变量,因此它将是一个整数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多