Python基礎之二函數

# coding: utf-8
            ###############   調用函數     #############
#調用abs函數
a = abs(100)
print(a)

#調用max函數
a = max(1, 2)
print(a)
a = max(1, 2, 3, 4, 5, 6)
print(a)

#數據類型轉換
a = int('23')
print(a)
a = float('213.3')
print(a)
a = str(1324234)
print(a)
a = bool(1)
print(a)
a = bool('')
print(a)
a = abs
a = a(-1)
print(a)
            ###############   定義函數     #############
'''
定義一個函數使用def語句,一次寫出函數名,括號,括號中的參數和冒號然後在縮進塊中編寫函數體,返回值用return
'''
def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
a = my_abs(-3)
print(a)
#空函數
def nop():
    pass

#檢查函數類型
def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x
print(my_abs(8))

#返回多個值
import math
def move(x, y, step, angle = 0):
    nx = x + step * math.cos(angle);
    ny = y - step * math.sin(angle)
    return nx, ny
print(move(100, 100, 60, math.pi / 6))

            ###############   函數的參數     #############

'''
    定義函數時,把參數的名字和位置確定下來,函數的接口定義就完成了。對於函數的調用者來說,只需要知道如何傳遞正確的參數,
以及返回什麼樣的值就夠了,函數內部的複雜邏輯被封裝起來,調用者無需瞭解。
    Python中出了正常定義必要參數外,還可以使用默認參數,可變參數和關鍵字參數,使得函數定義歘來的接口,不但能處理複雜
參數,還可以簡化調用者的代碼
'''

#位置參數
def power(x):
    return x * x
print(power(5))

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
print(pow(2, 3))

#默認參數 注意:默認參數必須指向不變的對象
def power(x, n = 2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * n
    return s
print(power(9))

#可變參數 也就是傳入的參數的個數是可變的, 允許你傳入0個或任意個參數,這些可變參數在函數調用的時候自動組裝成一個tuple
def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
print(calc((1, 3, 5, 6, 67)))
print(calc([4, 5, 6, 7, 56]))

def calc(*number):
    sum = 0
    for n in number:
        sum = sum + n * n
    return sum
print(calc(4, 4, 6, 23))

#關鍵字參數  允許你傳入0或者多個喊參數名的參數, 這些關鍵字參數在函數內部組裝爲一個dict
def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
print(person("張三", 34))

extra = {'city': 'Beijing', 'job': 'engineer'}
person('Jack', 34, **extra)

#命名關鍵字參數
def person(name, age, **kw):
    if 'city' in kw:
        print('有city')
    if 'job' in kw:
        print('有job參數')
    print('name:', name, 'age:', age, 'other:', kw)


    ###############   遞歸函數     #############

'''
在函數內部,可以調用其他函數, 如果函數內部調用自身,這個函數就是遞歸函數
'''
def fact(n):
    if n == 1:
        return 1
    return n * fact(n - 1)
print(fact(45))

更多精彩內容訪問個人站點www.gaocaishun.cn

發佈了154 篇原創文章 · 獲贊 173 · 訪問量 132萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章