20191109Python打卡學習 函式

2021-09-29 11:52:32 字數 3267 閱讀 1411

用def來宣告函式。

def

say_hello()

:print

('hello world!'

)

輸出:

hello world!

位置引數

是按照引數的位置來傳遞引數的值。

def

print_max

(a,b)

:if a > b:

print

(' is maximum'

.format

(a))

elif aprint

(' is maximum'

.format

(b))

else

:print

(' is equals to '

.format

(a,b)

) print_max(1,

3)

輸出:

3 is maximum

命名引數

指定引數的名字,可以調整引數的位置。

函式定義時,可以給引數乙個值。當呼叫時,該引數並示給出的情況下,使用預設值。有預設值的引數應該在沒有預設值引數的右邊,否則會報錯。

def

say(message,times=1)

:print

(message * times)

say(

'hello'

)say(

'world',5

)

輸出:

hello

worldworldworldworldworld

def

say(times=

1,message)

:print

(message * times)

輸出:

file 「」, line 1

def say(times=1,message):

^syntaxerror: invalid character in identifier

def

(l=)

: 1)

return l

print

))print

))print

('_____'

)print))

print))

print

))

輸出:

[1][1]

[1][1, 1]

[1, 1, 1]

遇到希望使用可變物件作為引數預設值的情況,需要使用none作為預設值。在函式中判斷是否為none,是的話再對引數做預設值處理。以此模式來避免上述問題。

def

(l=none):

if l is

none

:

l = 1)

return l

print

))print

))print

('_____'

)print))

print

))

輸出:

[1][1]

[1][1]

在函式內定義的變數稱為區域性變數,在函式外不能呼叫。對區域性變數的修改不影響全域性變數。

x=

50def

func

(x):

print

('change local x to '

.format

(x))

func(2)

print

(x)

輸出:

change local x to 2

50在模組內定義的變數叫全域性變數,全域性可見,在函式體內可以引用全域性變數。

函式可以用global來宣告全域性變數。

x=

50def

func()

:print

('x is '

.format

(x))

func(

)

輸出:

x is 50

函式內定義區域性變數

x=

50def

func()

:global x

print

('x is '

.format

(x))

x =2print

('changed x to '

.format

(x))

print

('x is before function.'

.format

(x))

func(

)print

('x is after function.'

.format

(x))

輸出:

x is 50 before function.

x is 50

changed x to 2

x is 2 after function.

變數的可見範圍叫做變數的作用域。區域性變數的作用域在函式內,全域性變數的作用域在模組內。作用域的基本原則是,內層作用域可以訪問外部作用域的變數,反之外層不可訪問內層變數。

如果兩個作用域內有同乙個名字,那麼內層的起作用。

x=

1def

func()

:print

(x) x=

2func(

)

unboundlocalerror traceback (most recent call last)

in ()

3 print(x)

4 x=2

----> 5 func()

in func()

1 x=1

2 def func():

----> 3 print(x)

4 x=2

5 func()

unboundlocalerror: local variable 『x』 referenced before assignment

x=

1def

func()

:print

(x)func(

)

輸出:

1

python手工打碼 Python學習 打碼平台

打碼平台介紹 優點 1.便宜 2.使用簡單 3.識別率高 平台介紹 極驗驗證碼智慧型識別輔助 超級鷹 打碼兔 若快打碼 等等 流程圖 使用者賬號用於登入,充值,平台是收費的 1元 1000分 開發者 新增我的軟體,獲取通訊秘鑰 檢視驗證碼型別 題分 使用者 充值 12306的驗證碼demoimpor...

python打包編譯 python編譯及打包

0 背景 python是一種物件導向的解釋型計算機程式語言,具有豐富和強大的庫,使用其開發產品快速高效。python的解釋特性是將py編譯為獨有的二進位制編碼pyc檔案,然後對pyc中的指令進行解釋執行,但是pyc的反編譯卻非常簡單,可直接反編譯為原始碼,當需要將產品發布到外部環境的時候,原始碼的保...

python打不出中文 Python輸入中文的問題

我寫了乙個爬烏雲漏洞庫的爬蟲,其url形式為公司名稱 page 1,程式最後raw input處輸入公司名稱即可跑出該公司的漏洞。現在的問題是中文編碼的問題沒解決好,如果公司的名稱是英文如rising就可以,如果是中文就報錯。求各位大大指點 coding utf 8 import sys reloa...