def greet_user()
print("hello!")
greet_user()
>>hello!
def display_message():
print(f'函数很重要,要认真学习')
print(display_message)
>> <function __main__.display_message()>
display_message()
>> 函数很重要,要认真学习
import random # import 导入代码库,random -随机数,标准库中的代码
# pc随机出两个数
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
print(num1, num2)
1.函数定义
- 函数,将重复的东西打包,以便后续测试及修改代码时方便
- 函数,是指一个量随着另一个量的变化而变化,或者说是一个量中包含另一个量
def function_name(s):
statement(s) #---代码语句,或其他函数,带(s)为调用,Call
- 函数都有一个返回值,return
# 定义一个函数,电脑随机选数,函数这一部分代码相当于一个小的系统,有输入和输出,return x ,即返回X,如不写即为none
def choose_num():
#注意标点符号要是在英文输入的模式下,即英文下的冒号
num = random.randint(1, 110)
return num
print(choose_num()) # 这一步即为函数的调用,有参数的情况下要添加参数,没有参数的情况下括号不能丢
print(choose_num()) # notebook下打印多个值,添加print
def choose_num(start, end):
num = random.randint(start, end) # 函数参数
return num # 返回num
choose_num(3, 90) # 函数参数调用: 3 → start, 90 → end
2.几种函数参数的用法
- 1) 默认参数 ```python def choose_num(start, end=120): # end= 120 默认参数即已经定义OK的 num = random.randint(start,end) return num
choose_num(2) # 参数的传递,2 → start ,一般都是按位置直接传递
```python
def choose_num(start=3, end): # 默认参数要放在非默认参数的后面!!! 此处错误,默认参数放在了非默认参数前面
num = random.randint(start, end)
return num
File "<ipython-input-61-c4f3ac5a1b46>", line 1
def choose_num(start=3, end): # 默认参数要放在非默认参数的后面!!! 此处错误,默认参数放在了非默认参数前面
^
SyntaxError: non-default argument follows default argument
def choose_num(start, end=100, n=6): #默认循环 n = 6 (次)
numbers = [] # 定义一个空列表
for x in range(n): # for 循环,n = 6 ,即循环6次
num = random.randint(start, end)
numbers.append(num) # append -- 将电脑随机选出的数num 添加到空列表numbers[]中去
return numbers # 函数返回值numbers[],列表
choose_num(3) #函数调用,参数传递:3 → start
def f(a, L=[]): L.append(a) return L
print(f(1)) print(f(3)) print(f(5)) # 此种情况是在列表上直接追加
[1] [1, 3] [1, 3, 5]
def f(a, L=None): L.append(a) return L
f(3)
AttributeError Traceback (most recent call last)
<ipython-input-2-068fe148bd6b> in <module>
3 return L
4
----> 5 f(3)
<ipython-input-2-068fe148bd6b> in f(a, L)
1 def f(a, L=None):
----> 2 L.append(a)
3 return L
4
5 f(3)
AttributeError: 'NoneType' object has no attribute 'append'
def f(a, L=None): # L定义默认参数为空None if L is None: # 用 if xxx is xxx ,进行判断 L = [] L.append(a) return L
print(f(1)) print(f(3)) print(f(7))
[1] [3] [7]
<a name="K48FA"></a>
## 关键词参数 (K = V)
<br />
```python
def car(color, price="10", user="yangjiangyun"): #定义一个Car 函数,price & user 使用默认参数
print(f'{user}有一辆{color}色的车,价值{price}块.') # 注意 f' 的使用方法
car('白') # 函数调用,使用默认参数,且‘白’→ Color ,位置参数
car('红', '30', 'YC') # 默认参数可以被覆盖,如,此处函数调用参数为:对应位置传递
car(color='blue', price='80') #使用关键词参数
car(price= 100) # 非默认参数必须赋值,color → 否则代码会报错异常
-----------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-0b6e25842bb5> in <module>
----> 1 car(price= 100) # 非默认参数必须赋值,color → 否则代码会报错异常
TypeError: car() missing 1 required positional argument: 'color'
函数任意参数相关
# *args **kwargs: args → tuple ,kwargs → dict
def car(*args):
print(args) # 打印出参数
for k in args: # for 循环
print(k)
car('red', 10, 'YC')
('red', 10, 'YC')
red
10
YC
def car(**kw): # *的个数不一样,** → dict ,K = V
for k,v in kw.items(): # for 循环 KW 参数,并打印输出
print(f'{k}::{v}')
car(color='red', price=1000, user='YC') #函数参数的传递,传递字典K=V
color::red
price::1000
user::YC
def car(*args, **kw): # 函数传递任意参数的写法,通过 * 来定义
print('args:',args)
print('kw:', kw)
for k in args:
print(k)
for k,v in kw.items():
print(f'{k}--{v}')
car('sasa', 'T', color='red', price=1000, user='YC') # 函数 car 参数传递
args: ('sasa', 'T')
kw: {'color': 'red', 'price': 1000, 'user': 'YC'}
sasa
T
color--red
price--1000
user--YC
kwargs = {'color':'red', 'price':30} # 字典传入函数,两个 **
def car(**kw):
print(kw)
car(**kwargs) # 函数调用,参数传递
{'color': 'red', 'price': 30}
def car(color='blue', * , price): # price 这个参数必须要传递时,前面添加一个 * ,必须要某个参数传递时使用此方法
print(color, price)
# car() 必须要对price这个参数进行传递,否则程序会报错
car(price=999)
Lambda表达式,匿名函数使用
# lambda 变量名:对变量的操作
lambda x: x+1
add = lambda x: x+1 #lambda 表达式赋值给变量add 进行操作
add(17)
my_list = [1,2,3,4,5,6,7,8,9] # 找出列表中的所有奇数,并返回一个新的列表 --- 《列表导入函数参数中》
def odd(*L):
new_list = [] # 建立一个空的列表
for k in L:
if k % 2 == 1:
new_list.append(k) # 对新列表进行追加操作,append()
return new_list # 返回K追加后的新列表
odd(*my_list) # my_list 函数参数传递到 L 中去,→ for 循环 → 对 K 操作
# filter ,"过滤",python中的内置函数
filter(lambda x: x%2 == 1, my_list)
list(filter(lambda x: x%2 == 1, my_list)) # 用list包裹,生成列表输出
函数注释与文档说明(annotation, doc)
def add(x, y):
"""Add x and y together""" # 文档说明:写在函数体的第一行,即 function def 后,函数体之前
return x+y
add.__doc__ # doc两边都是双下划线
def add(x:int, y:"这个数随便")- > int: # 函数注释,参数中冒号(:)后即函数注释,X:int
"""Add x and y together.
多添加一行"""
return x + y
pass ,抢地盘,抢位置,凑语法
python
def add():
pass
if True:
pass
函数作用域
1.变量作用域
2.函数嵌套
3.函数闭包,或者闭包函数
# 变量作用域,在自己的范围内干自己的事
# LEGB: Local→本地(局部), Enclosing→封闭, Global→全局, Builtin→内置
x = 1 # 此处X为全局变量
def add():
x += 1 #局部变量赋值错误,X = X + 1
print(x)
add()
-----------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-26-45625ce07266> in <module>
7 print(x)
8
----> 9 add()
<ipython-input-26-45625ce07266> in add()
4 x = 1 # 此处X为全局变量
5 def add():
----> 6 x += 1 #局部变量赋值错误,X = X + 1
7 print(x)
8
UnboundLocalError: local variable 'x' referenced before assignment
全局变量
python
x = 99
def add():
print(x) #本地作用域中可以取到全局变量
add()
error_list = [2,3,5] # error_list 全局变量
def big_list(): # 定义函数 big_list
error_list.append(88) # error_list,列表中追加 88
print(error_list)
big_list() # 函数调用
函数嵌套
函数是python里面的一级对象,可以用在任何地方,比如函数里面,这时候的作用域属于封闭作用域。
一级对象:
1,在运行时创建
2.能赋值给变量或数据结构
3.能作为参数传给函数
4.能作为函数的返回结果
def calc(x, y):
def add(x, y):
print('x+y:', x + y)
def sub(x, y):
print('x-y:', x - y)
def mul(x, y):
print('x*y:', x * y)
add(x, y)
sub(x, y)
return mul
calc(3, 5)
x+y: 8
x-y: -2
<function __main__.calc.<locals>.mul(x, y)>
x+y: 8
x-y: -2
c(2, 4) # 函数返回出来,即return mul
x*y: 8
# 闭包(函数)→ 给嵌套函数里面加了个变量,同时返回本身的一个函数,这个整体称之为闭包函数
def hello():
s = 'YC' # 给嵌套函数加个变量名 S ,自有变量
def say(): # 定义函数
# s += '在干啥?'
print(s)
return say # 返回嵌套本身的函数say