python 学习 1

来源:互联网 发布:银联快捷支付 网络支付 编辑:程序博客网 时间:2024/05/01 15:58

https://pythonmonk.com/

定义函数计算传入参数中数字的个数

def count_digits(n):
    """Counts the number of digits in the given number.
    
        >>> count_digits(5)
        1
        >>> count_digits(42)
        2
        >>> count_digits(9876543210)
        10
        >>> count_digits(2 ** 100)
        31
    """
    # your code here
    tempstr=str(n)
    count=0
    for i in range(0,len(tempstr)):
        if tempstr[i]<='9' and tempstr[i]>='0':
            global count
            count=count+1
            
    return count


在首次写法中,丢失global count 使的函数内部count=count+1 出现语法错误

0 0
原创粉丝点击