求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"

时间:2022-11-02
本文介绍了求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我是 python (PYTHON 3.4.2) 的新手,我正在尝试制作一个程序来添加和除以查找用户输入的平均值或平均值,但我不知道如何添加我收到的号码.

I'm new to python (PYTHON 3.4.2) and I'm trying to make a program that adds and divides to find the average or the mean of a user's input, but I can't figure out how to add the numbers I receive.

当我在命令提示符下打开程序时,它会接受我输入的数字,并且如果我使用打印功能也会打印它,但它不会将数字相加.

When I open the program at the command prompt it accepts the numbers I input and would print it also if I use a print function, but it will not sum the numbers up.

我收到此错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

我的代码如下:

#Take the user's input
numbers = input("Enter your numbers followed by commas: ")
sum([numbers])

任何帮助将不胜感激.

推荐答案

input 将输入作为字符串

>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,2,5,8
>>> sum(map(int,numbers.split(',')))
16

你告诉用户输入用逗号分隔,所以你需要用逗号分割字符串,然后将它们转换为 int 然后求和

you are telling user to give input saperated by comma, so you need to split the string with comma, then convert them to int then sum it

演示:

>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,3,5,6
>>> numbers
'1,3,5,6'   # you can see its string
# you need to split it
>>> numbers = numbers.split(',')
>>> numbers
['1', '3', '5', '6']
# now you need to convert each element to integer
>>> numbers = [ x for x in map(int,numbers) ]
or
# if you are confused with map function use this:
>>> numbers  = [ int(x) for x in numbers ]
>>> numbers
[1, 3, 5, 6]
#now you can use sum function
>>>sum(numbers)
15

这篇关于求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:获取 Pandas 列的总数 下一条:python 的 sum() 和非整数值

相关文章

最新文章