1. 程式人生 > >python 學習 1

python 學習 1

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 出現語法錯誤