Python基礎語法篇#3
(修改过)
IPFS
function(函式) -- 類似於數學公式的概念
想像一下,假設我想顯示一個資料概況,如下圖,有兩個資料的話,我不是就要打同樣的東西兩遍嗎(要改參數),以此類推,一多就會很煩,還會忘記自己打了甚麼,這時候就是交給function的時候,主要用於大型程式庫。
語法: def functionName():
一樣用 : 和縮排來表示function區塊,()內要填的是參數

- 輸入參數名稱
呼叫function時可以直接輸入參數名稱,這樣可以不用管參數的順序

- 參數預設值
參數可以使用預設值,(有設值的參數必須是參數串列的最後)

- 不定數目參數函式
可用在不確定參數會有多少時

全域變數和區域變數
若有相同名稱的全域和區域變數,以區域變數為優先,
以下範例示範在function裡面沒有定義變數var2,
可是因為var2是全域變數所以在function裡面還是可以讀取到var2。

Lambda函式 -- 也就是匿名函式
Lambda函式,適用於小型的運算,不需要定義名稱,只有一行運算式,語法非常簡潔,功能強大。
ex1 : lambda (參數) : 運算式

ex2: 就只是把ex1的lambda放進去print加上給它參數而已

ex3 :

import -- 做大型專案的居家必備良藥阿!
想要引用其他module裡面的function、class、variable。就需要使用import的方式引用進來。類似要引用numpy、Pandas、Matplotlib...
import的方法有四種
1. import 套件名稱 2. from 套件名稱 import * (*為函數名稱) 3. from 套件名稱 import 函式1, 函式2, ... (適用於兩個套件有相同的函數名稱) 4. import 套件名稱 as 別名

內建函數,可以自己試試,大部分情況用不到
example1 = abs(-10) print(example1) #取得絕對值輸出10 example2 = chr(66) print(example2) #取得整數66的字元輸出B,ASCII的編碼模式 example3 = divmod(33,6) print(example3) #取得33除以6的商數和餘數輸出 (5, 3) example4 = float(33) print(example4) #轉成浮點數輸出 33.0 example5 = hex(33) print(example5) #轉成16進位輸出 0x21 example6 = int(22.79) print(example6) #轉成整數(無條件捨去)輸出 22 example7 = oct(33) print(example7) #轉成八進位輸出 0o41 example8 = ord("B") print(example8) #取得Unicode編碼輸出 66 example9 = pow(2,5) print(example9) #取得2的5次方輸出 32 example10 = round(22.79) print(example10) #轉成整數(四捨五入)輸出 23 example11 = sum([11,22,33,44]) print(example11) #取得list的總和輸出 110
更深的解說,個人覺得他講得不錯 - Python import 簡易教學
Python 的 Import 陷阱
我就是在偷懶不發教學文(X
喜欢我的作品吗?别忘了给予支持与赞赏,让我知道在创作的路上有你陪伴,一起延续这份热忱!



- 来自作者
- 相关推荐