1. 程式人生 > >6、Python_函式呼叫與定義

6、Python_函式呼叫與定義

1、基本常用函式:

    abs(100)---->絕對值

    max(1,2)---->取大值

    int('123') ---->型別轉換

    float('123') ---->型別轉換

    str(123) ---->型別轉換

    bool(1) ---->型別轉換

    hex(18)---->十進位制轉十六進位制

    power(2)---->開平方

    strip()------->字串兩頭去空格

    sum(list)-------->求和

    string.upper()----->轉大寫

    string.lower()----->轉小寫

    string.find('c')------>找到字元在字串中的索引位置

 

2、函式賦值:

    a = abs;

    a(-1)

    ------------>結果:1

 

3、函式定義(abstest.py):

    def my_abs(x):

        if x >= 0:

            return x

        else :

            return -x

    函式無return語句,預設返回None。return None 可以簡寫成return

 

4、函式引入並呼叫:

    #引入

    from abstest import my_abs

    #呼叫

    my_abs(-9)

 

5、空函式:

    def nop():

        pass

    pass可以當語句佔位符

    isinstance()---->用於檢查型別是否匹配

 

6、返回多個值:

    def move(x,y,step,angle):

        nx = x + step * math.cos(angle)

        ny = y - step * math.sin(angle)

        return nx,ny

    其實返回的是一個tuple

    t = (12,333)