-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFunctions
More file actions
306 lines (230 loc) · 7.61 KB
/
Functions
File metadata and controls
306 lines (230 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
1.what is a function?
- a process for executing a task, reusable
- useful for re-act similar stuff
#stay DRY - Don't Repeat Yourself!
(WET - write everything twice)
#*Abstract away* code for other users
2.function structure
def name_of_function():
#block of runnable code
def say_hi():
print("what is your name?")
name = input()
print(f"hi, {name}")
say_hi()
def sing_happy_birthday():
print("Happy birthday to you")
print("Happy birthday to you")
print("Happy birthday dear you")
print("Happy birthday to you")
for i in range(2,4):
sing_happy_birthday()
3. return value for functions
#return will exit the function, anthing after return won't be touched
#return will outputs whatever value is placed after the return keyword
#return pops the function off of the call stack
def square_of_7():
return 7**2
result = square_of_7()
print(result)
from random import random
def filp_coin():
#random() generate random number 0 - 1 (no 1)
if(random() > 0.5):
return "heads"
else :
return "tails"
#print(filp_coin())
#if has the same function definination, it will overwrite and pick the bottom one
def filp_coin():
#random() generate random number 0 - 1 (no 1)
if(random() > 0.5):
return "HEADS"
else :
return "TAILS"
print(filp_coin())
#只有一个if条件时if需要在最后,这是为啥?。。
def generate_evens():
return [x for x in range(1,50) if x % 2 == 0 ]
4. function parameters
def square(num):
return num * num
print(square(4)) #16
def add(a,b):
return a + b
print(add(2,3)) #5
#it is better to make function parameter name meaningful
#parameter vs arguments
parameter is a variable in function defination
argument is the actual value of this variable that gets passed to function
5.default parameters
#give power a default value -- the thing happened to pop()
def exponent(num,power = 2):
return num ** power
print(exponent(2,3))
print(exponent(3)) #9
# the default parameter can be anything, even other functions!
eg : just the name of function, no() aftert name!
def add(a,b):
return a + b
def math(a,b,fn = add):
return fn(a,b)
def substract(a,b):
return a - b
print(math(2,3)) #5
print(math(2,3,substract)) # -1
#def math(fn = add, a,b) #error, default has to be at the end or 一路向下
#因为python是按照顺序assign para 的
6.keyword argument
#can specify the argument -- only if we know the name of parameters
print(exponent(power=2, num=5)) #25
#more expilicit, a little more flexibility
#it is useful when passing a dictionary to a function and unpacking it's values
#注意与 default para 区别
7.scope
#where the variables can be accessed
-variable created in functions are scoped in that function! --only avaiable in that function
-global not in a function
total = 0
def increment():
total += 1
return total
increment() #ERROR! local variable 'total' referenced before assignment
#it expect a local variable
total = 0
def increment():
global total #this key word will work
total += 1
return total
print(increment()) # 1
print(increment()) # 2
--nonlocal #let us modify a parent's variables in a child(AKA nested) function
def outer():
count = 0 #since count is not a gobal variable
def inner():
nonlocal count
count += 1
return count
return inner()
8. it is better to write docs for function by using ''' in a function and use function.__doc__ (are dounle underscores) to access it
def exponent(num,power = 2):
'''A simple function to calculate exps, the second para is power, default as 2'''
return num ** power
#double underscore!!!!
print(exponent.__doc__)
9.function exercise
A.
def last_element(para):
if(len(para) != 0):
return para[len(para)-1]
return None
#更简单的写法
def last_element(l):
if l:
return l[-1]
return None
B. is_pali?(空格和大小写freeB)
def is_palindrome(string):
stripped = string.replace(" ", "").upper()
return stripped == stripped[::-1]
C. 注意区别 for 和 list comprehension ,普通的for loop 没法把if写在一行
def multiply_even_numbers(l):
res = 1
for i in l :
if (i % 2 == 0) :
res *= i
return res
D.只大写首字母
def capitalize(string):
return string[0].upper()+string[1:]
E.注意区别bool和truthy
def compact(l):
return[ k for k in l if k]
#错误写法,只判断是不是等于True
def compact(l):
return[ k for k in l if k == True]
10. *args
#A special operator we can pass to a function
#gathers remaining arguments as a tuple
#just start with * (don't need to call args)
def sum_all_nums0(*args):
print(args)
sum_all_nums0(4,6) #(4, 6)
#now it will work with all numbers of arguments
def sum_all_nums(*args):
total = 0
for num in args:
total += num
return total
print(sum_all_nums(4,6,8,4)) #22
print(sum_all_nums(4,6)) #10
def sum_all_nums2(num1, num2, *args):
total = 0
for num in args:
total += num
return total
print(sum_all_nums2(4,6,8,4)) #12 -- this way num1 and num2 is ignored
print(sum_all_nums2(4,6)) #0 --empty tuple
def ensure_correct_info(*args):
if "colt" in args and "steel" in args:
return "welcome back colt"
return"who you are"
print(ensure_correct_info("hello", 78)) #who you are
print(ensure_correct_info("hello", "colt")) #who you are
print(ensure_correct_info("hello", "Colt", "steel")) #who you are --case sensitive
print(ensure_correct_info("hello", "colt", "steel")) #welcome back colt
11. **kwargs
#gathers remaining keyword arguments as a dictionary
def fav_colors(**kwargs):
print(kwargs)
for person, color in kwargs.items():
print(f"{person}'s favoarte color is {color}")
fav_colors(colt = "purp", ruby = "red", evennly = "tea") #{'colt': 'purp', 'ruby': 'red', 'evennly': 'tea'}
#传参数 colt 不可以带引号,--SyntaxError: keyword can't be an expression
'''
colt's favoarte color is purp
ruby's favoarte color is red
evennly's favoarte color is tea
'''
12.parameter ordering
1-parameters
2-*args
3-default parameters
4-**kwargs
def display_info(a, b, *args, instructor = "colt", **kwargs):
return [a,b,args,instructor,kwargs]
print(display_info(1,2,3,last_name = "steele", job = "instructor"))
#[1, 2, (3,), 'colt', {'last_name': 'steele', 'job': 'instructor'}]
#注意只有一个元素的tuple
13. use * as an argument: argument unpacking
def sum_all_values (*args):
print(args) # (1, 2, 3, 4, 5, 6)
total = 0
for num in args:
total += num
print(total)
nums = [1,2,3,4,5,6]
#sum_all_values(nums) #TypeError: unsupported operand type(s) for +=: 'int' and 'list'
#args: ([1, 2, 3, 4, 5, 6],) ---只有一个元素的tuple, num是第一个元素(list),无法与total(int)相加
#解决方法:
sum_all_values(*nums) #21
14.use ** to unpack dictionary
def display_names(first,second):
print(f"{first} says hello to {second}")
names = {"first": "colt", "second":"Rust"} #should be the name passed in para
display_names(**names) #colt says hello to Rust
#exercise: 学习get() 的用法 --可以传两个参数:get(要查的值,是None的话设为 default)
def calculate(**kwargs):
operation_lookup = {
'add': kwargs.get('first', 0) + kwargs.get('second', 0),
'subtract': kwargs.get('first', 0) - kwargs.get('second', 0),
'divide': kwargs.get('first', 0) / kwargs.get('second', 0),
'multiply': kwargs.get('first', 0) * kwargs.get('second', 0)
}
is_float = kwargs.get('make_float', False)
operation_value = operation_lookup[kwargs.get('operation', '')]
if is_float:
final = "{} {}".format(kwargs.get('message','The result is'), float(operation_value))
else:
final = "{} {}".format(kwargs.get('message','The result is'), int(operation_value))
return final