问答详情
源自:9-5 Python函数参数

我不会啊不会啊

def func(x):
    if isinstance(x,list):
        sum=0
        for a in x:
            if isinstance(a,float) or isinstance(a,int):
                sum+=a
            else:
                sum='类型错误,list中有非floa或非int型的元素'
        return sum           
    if  isinstance(x,tuple):
        sum=0
        for a in x:
            if isinstance(a,float) or isinstance(a,int):
                sum+=a*a
            else:
                sum='类型错误,tuple中有非floa或非int型的元素'
        return sum
    else:
        sum='类型错误'
    return sum
   
       
a=[1,2,3,4,5,'a']
b=(1,2,3,4,5,'b')
c={'a':1}
print(func(a))
print(func(b))
print(func(c))
           

提问者:醉风飒 2021-01-13 10:03

个回答

  • Augenst
    2021-01-13 10:04:09
    已采纳

    优秀!!

  • Augenst
    2021-01-13 10:04:53

    def func(x):

        if isinstance(x,list):

            sum1=0

            for a in x:

                if isinstance(a,int) or isinstance(a,float):

                    sum1+=a

            return sum1

        if isinstance(x,tuple):

            sum2=1

            for b in x:

                if isinstance(b,int) or isinstance(b,float):

                    sum2=sum2*b

            return sum2

                

    L=[1,2,3,4,5]

    print (func(L))

    S=(1,2,3,4,5)

    print (func(S))

    D=[1,2,3,4,'sd']

    print (func(D))