简体   繁体   中英

How to solve TypeError: unsupported operand type(s) for +: 'float' and 'tuple'

the propose of this code is to use several functions to find the statical information for a list made by the user's input.

def getNum():
    nums = []
    iNumStr = input("please input the number(use enter to exist): ")
    while iNumStr != "":
        nums.append(eval(iNumStr))
        iNumStr = input("please input the number(use enter to exist): ")
    print(type(nums))
    return nums




def mean(numbers):
    s = 0.0
    for num in numbers:
        s = s + num
    return s / len(numbers)


def dev(numbers, mean):
    sdev = 0.0
    for num in numbers:
        sdev = sdev + (num - mean) ** 2
    return pow(sdev / (len(numbers) - 1), 0.5)


def median(numbers):
    sorted(numbers)
    size = len(numbers)
    if size % 2 == 0:
        med = (numbers[size//2-1]+numbers[size//2])/2
    else:
        med = numbers[size//2]
    return  med
n = getNum()
m = mean(n)
print("ave{},dev{:.2},med{}.".format(m,dev(n,m),median(n)))

the problem is it shows me

in mean
    s = s + num
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'

and sames there are same problems in other function block.

The eval function evaluates passed arguments as python expressions . Probably you are typing your float numbers like this '4,4', '4,5' etc. eval() evaluates it like tuples. It actually appends tuples to your list. Instead of typing floats with commas type them with dots '4.5', '4.6'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM