python 入門學習(四)

2022-05-18 11:05:20 字數 2860 閱讀 5386

函式:

定義函式

#

area.py

from math import

pidef

area(radius):

"""return the area of a circle with the given radius.

"""return pi * radius ** 2

>>> ******************************== restart ******************************==

>>>

>>> area(5.5)

95.03317777109125

>>> print(area.__doc__

)return the area of a circle with the given radius.

>>>

doctest#可用於自動執行文件字串中的python示例**

全域性變數訪問時一定要加上global

#

error

name = '

jack

'def

say_hello():

print('

hello

' + name + '!'

)def

change_name(new_name):

name = new_name

>>>say_hello()

hello jack!

>>> change_name('

mary')

>>>say_hello()

hello jack!

#

correct

name = '

jack

'def

say_hello():

print('

hello

' + name + '!'

)def

change_name(new_name):

global

name

name = new_name

>>>say_hello()

hello jack!

>>> change_name('

mary')

>>>say_hello()

hello mary!

main():被認為是程式的起點,可選不一定要。執行時必須輸入main()

python中引數的傳遞都是按引用傳參,python支援按值傳參

在引用傳參中,無法修改引數的值。下面的函式起作用:

#

reference.py

defset1(x):

x = 1

>>> ******************************== restart ******************************==

>>>

>>> y = 5

>>>set1(y)

>>>y

5

函式引數預設值:

注意:包含預設引數的形參一定要放在無缺省引數的形參後面

只有第一次呼叫函式時給預設引數賦值! #還不理解,先記下來

#

greetings.py

def greet(name, greeting = '

hello'):

print(greeting, name + '

!')

>>> greet('

bob'

)hello bob!

>>> greet('

bob', '

good morning')

good morning bob!

使用關鍵字傳參,即在使用時也指明形參,可以不理會順序,很好用:

#

greetings.py

def greet(name = '

bob', greeting = '

hello'):

print(greeting, name + '

!')

>>> greet(greeting = '

good evening

', name = '

mary')

good evening mary!

>>> greet(greeting = '

good evening')

good evening bob!

也可以用模組化的方式來呼叫,模組中不包括main函式

>>> import

greetings

>>>greetings.greet()

hello bob!

>>>dir(greetings)['

__builtins__

', '

__cached__

', '

__doc__

', '

__file__

', '

__loader__

', '

__name__

', '

__package__

', '

__spec__

', '

greet

']

Python基礎入門(四)

函式即變數高階函式 巢狀函式 裝飾器 裝飾器 定義 本質就是函式,裝飾其他函式 就是為其他函式新增附加功能 1.不能修改被裝飾函式的源 2.不能修改被裝飾函式的呼叫方式 高階函式 巢狀函式 把乙個函式名當做實參傳給另外乙個函式 返回值中包含函式名 不修改函式的呼叫方式 沒有修改被裝飾函式的源 但是改...

python基礎入門(四)

呼叫上一級非全域性變數用 nonlocal 函式的作用域只跟函式宣告時定義的作用域有關,跟函式的呼叫位置無任何關係 name 111 deffoo name 222 defbar name 333 print name deftt print name return tt return bar r1...

Python入門系列(四)

今天我們分享一下python中的字串格式化,python的字串格式化,大致分為兩種 使用 對字串進行格式化 s 字串,格式化字串,並提供佔位符 name 張三 print 我的名字是 s name 我的名字是 張三為了方便擴充套件,我們把這個例子再次拓展一下,name 張三 age 30 score...