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

后端 未结 5 1512
梦毁少年i
梦毁少年i 2020-12-03 13:07

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

相关标签:
5条回答
  • 2020-12-03 13:40

    input takes a input as string

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

    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

    demo:

    >>> 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
    
    0 讨论(0)
  • First you need to convert elements of "numbers" to int, no need to strip the comma or whitespaces. This code is pretty straight forward and works fine.

    numbers = input("Enter your numbers followed by commas: ")
    
    numbers_int = [int(x) for x in numbers]
    
    numbers_sum = sum(numbers_int)
    
    print numbers_sum
    
    0 讨论(0)
  • 2020-12-03 13:46

    Try the following code. It works for me. Actually input() tries to run the input as a Python expression. But the raw_input() takes the input as string. input() exists in Python 3.x.You can find more details here

    numbers = input("Enter your numbers followed by commas: ") ## takes numbers as input as expression
    print sum([i for i in numbers]) ## list comprehension to convert the numbers into invisible list. This is done because `sum()` runs only on iterable and list is iterable.
    

    Output:

    Enter your numbers followed by commas: 1,2,3,4
    10
    
    0 讨论(0)
  • 2020-12-03 13:48

    input will give you string, and you are trying to concat string with int.

    0 讨论(0)
  • 2020-12-03 13:49

    Simple: the list elements are stored as string :) So you have to convert all of them to int

    0 讨论(0)
提交回复
热议问题