Viraj Kaulkar Viraj Kaulkar - 3 months ago 9
Python Question

I want to print integer variables string separated by some string in Python3

I am trying to print 3 integer variables separated by some string. But it is giving me an error


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


My attempt:

def unpack_values(grades):
first, *middle, last = grades
avg = sum(middle)/len(middle)
print(str(first)+"-------"+str(avg)+" ---- "+str(last))

unpack_values(['10', '20', '30', '40', '50'])

Answer

Because you're passing list of strings. Your code should look like:

def unpack_values(grades):
    first, *middle, last = map(int, grades)
    avg = sum(middle)/len(middle)
    print('{}-------{} ---- {}'.format(first, avg, last))

unpack_values(['10', '20', '30', '40', '50'])