Skip to main content

2-7 函數

函數(函式,function)是邏輯結構化和過程化的一種編程方法

如何自定函數 ?

        def 函數名稱 (參數1,  參數2,  ....) :
               函數的詳細內容
                  :
                return 傳回值

 

如何呼叫自定函數 ? 

        函數名稱(參數1,  參數2,  ....)
        傳回值 = 函數名稱(參數1,  參數2,  ....)

 

範例1:輸入3小時25分,顯示等於多少秒數

def myfunc (h, m):
    value = (h * 60 + m) * 60
    return value


sec = myfunc(3, 25)
print (sec)

輸出結果為 12300

範例2:輸入圓的半徑,計算圓面積

def area(radius):
    result = radius * radius * 3.14
    return result


print(area(10))

輸出結果為 314.0

 

 

練習1:輸入兩個整數(例如首項=5、末項=10),計算兩數字之間(包含兩數字)所有整數總和     (參考答案 = 45 )

練習2: 輸入兩個整數(例如首項=5、末項=10),計算兩數字之間(包含兩數字)所有整數平方和 (參考答案=355)

 

練習3: 輸入兩個整數(首項=5、末項=10),計算兩數字之間(包含兩數字)所有奇數總和 (參考答案=21)

 


函數的三大好處

  • 代碼重複使用
  • 保持一致性
  • 可擴展性



可參考: https://ithelp.ithome.com.tw/articles/10187997

 


 

Python的內建函數

 

len() :回傳資料的長度或資料包含的元素數量
>>> len("This is a book.")
15

>>> a = ['a', 'b', 123]
>>> len(a)
3

 

max()、min():回傳最大值、最小值
>>> max (100, 500, 50)
500
>>> min (100, 500, 50)
50
>>> 

 

sorted():排序

排序規則:數字 < 大寫英文字母 < 小寫英文字母 < 中文

a=[3, 4, 1, 2, 5]
print(sorted(a))

如果是字串中的資料,也可以用「split」切開變成list,再去排序:

a="3 4 1 2 5 0"
b=a.split()
print(sorted(b))

 

type():顯示變數的資料型態
x = 123
y = 12.3
z = '123'
a = ['張三', '李四' , 123]
b = ('張三', '李四', 123)
c = {1:'一月', 2:'二月', 3:'三月'}
d = {'張三', '李四', 123, 123}

print (type(x))
print (type(y))
print (type(z))
print (type(a))
print (type(b))
print (type(c))
print (type(d))

輸出結果:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>