局部变量:
函数内部定义的变量,只能在函数内部使用
全局变量:
函数外部定义的变量,在哪都可以调用
1
'''
2
def get_wendu():
3
wendu = 33
4
return wendu
5
6
def print_wendu(wendu):
7
print('温度:%d'%wendu)
8
9
result = get_wendu()#函数返回值,在没有调用函数之前,用变量保存的话,没有意义
10
print_wendu(result)
11
'''
12
13
#定义一个全局变量:wendu
14
wendu =
0
15 def
get_wendu
():
16
#这个wendu只是与全局变量wendu同名,不可对全局变量进行修改
17
#wendu = 30
18
#使用global用来对全局变量的声明
19
global
wendu
20
wendu =
20
21
22 def
print_wendu
():
23
print
(
'温度:%d'
%wendu)
24
25
get_wendu()
26
print_wendu()
全局变量在函数内修改时应该先进行声明(golbal),否则默认为定义一个局部变量
缺省参数
#定义形参时,b给了默认的值,当不传值时,使用默认值,这就是缺省参数,缺省参数,要放在最后
def test(a,d,b = 1,c = 2):
result = a+b
test(10,1,2,3)
test(20,12)
test(2,4,c=5)
不定长参数
1 def
sum_nums
(a,b,*args):
#形参前加* ,不定长参数必须放在最后(以元组的方式保存)
2
print
(a)
3
print
(b)
4
print
(args)
5
result = a+b
6
for
num
in
args:
7
result += num
8
print
(
'和:%d'
%result)
9
print
(
'='
*
40
)
10
11
sum_nums(
12
,
13
,
14
,
15
,
16
)
12
13
sum_nums(
12
,
13
,
14
)
14
15
sum_nums(
12
,
13
)
16
17
#sum_nums(12) #错误,形参中至少要有2个实参
18
19 def
test
(a,b,c =
12
,*args,**kwargs):
#形参前加** ,以字典方式保存
20
print
(a)
21
print
(b)
22
print
(c)
23
print
(args)
24
print
(kwargs)
25
print
(
'-'
*
50
)
26
27
test(
12
,
13
,
14
,
15
,
16
,weight =
17
,age =
18
,high =
19
)
28
29
A = (
1
,
2
,
3
)
30
B = {
'name'
:
'jack'
,
'age'
:
18
}
31
test(
12
,
13
,
14
,A,B)
32
test(
12
,
13
,
14
,*A,**B)
#拆包
引用
查询内存地址
In [
1
]:
a =
11
In [
2
]:
b = a
In [
3
]: id
(a)
Out[
3
]:
4297641408
In [
4
]: id
(b)
Out[
4
]:
4297641408
阶乘
1
#阶乘
2
i =
1
3
result =
1
4
5 while
i<=
5
:
6
result *= i
7
i +=
1
8
print
(result)
9
10 def
jc
(num):
11
# 加判断限制函数,return返回值才可以继续乘下去
12
if
num >
1
:
13
return
num *jc(num-
1
)
14
else
:
15
return
num
16
result = jc(
6
)
17
print
(result)