1 全局变量
2 # a = 100#全局变量 少用全局变量 会一直占内存
3 # def test():
4 # global a
5 # a=1
6 # print(a)
7
8 # test()
9 # print(a)
10 """
11 def test():
12 global a
13 a=5
14
15 def test1():
16 c=a+5
17 return c
18
19 test()
20 res = test1()
21 print(res) #如果未调用test() 会报错 因为a未定义"""
22
23 def test():
24 L = []
25 for i in range(50):
26 if i % 2 ==0:
27 L.append(i)
28 return L
29
30 print(test())
31
32
33 函数
34 # 函数、方法
35 # 提高的代码复用性,简化代码
36 def hello():
37 print('hello')
38 def welcome(name,country = '中国'):
39 return name,country
40
41 def test():
42 return
43
44 print('没有写return:',hello())
45 print('return多个值的时候:',welcome('hym'))
46 print("return后面啥都不写:",test())
47
48 # def op_file(filename,content =None):
49 # with open(filename,"a+",encoding="utf-8") as f:
50 # f.seek(0)
51 # if content:
52 # f.write(content)
53 # else:
54 # result = f.read()
55 # return result
56 #
57 # print(op_file("student.txt"))
58
59 # 函数里面定义的变量都是局部变量,只能在函数内部生效
60 # 函数里面只要遇到return函数立即结束
61
62
63 函数参数
64 def send_sms(*args): #可选参数(参数组)不定长参数 接收到的是一个元组
65 print(args)
66
67
68 # send_sms() #返回空元组 不传参数时
69 # send_sms("130449484306") #传一个参数时
70 # send_sms(1304984306,13049484307) #传多个参数时
71
72 def send_sms2(**kwargs): #关键字参数 接收到的是一个字典
73 print(kwargs)
74
75 send_sms2(a=1,b=2,name="abc")
76 send_sms2()
77
78 # 必填参数(位置参数)
79 # 默认值参数
80 # 可选参数,参数组
81 # 关键字参数
82
83
84 函数练习
85 # def is_float(s):
86 # s = str(s)
87 # if s.count('.')==1:
88 # left,right = s.split('.')
89 # if left.isdigit() and right.isdigit():
90 # return True
91 # elif left.startswith('-') and left.count('-')==1 \
92 # and left[1:].isdigit() and right.isdigit():
93 # return True
94 # else:
95 # return False
96 # else:
97 # return False
98 #
99 #
100 # price = input("请输入价格:").strip() #去空
101 # result = is_float(price)
102 # if result:
103 # print("价格合法")
104 # else:
105 # print("价格不合法")
106
107 money = 500
108 def test(consume):
109 return money - consume
110
111 def test1(money):
112 return test(money) + money
113
114 money = test1(money)
115 print(money)
116