
函数:
定义函数
#area.py from math import pi
def 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
def set1(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']