python function and error
通过函数调用函数,并传递参数
def binary_operation(func,op1,op2):
return func(op1,op2)
def add(op1,op2):
return op1+op2
def sub(op1,op2):
return op1-op2
print(binary_operation(add,1,2))
print(binary_operation(sub,1,3))
# 产生函数的快捷凡是
def exp_factory(n):
def exp(a):
return a**n
return exp
suqare=exp_factory(2)
type(suqare)
exp_factory(2)(3) #两个括号的函数调用
程序是一步一步设计的
函数嵌套
from time import clock # clock return CPU time or real time
def timer(f): # 传入一个函数
def _f(*args):
t0=clock()
f(*args) # 任意参数
return clock()-t0
return _f
timer(binary_operation)(add,1,2)
指定输入参数的类型(防止输入量类型错误)
def greeting(name:str) ->str: # :str 参数的type -> str 返回值的type
return 'Hello '+str(name) # 强制装换
greeting('zyj')
lambda (anonymous function tiny function)
# Lambda function can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required
binary_operation(lambda op1,op2:op1*op2,2,4) # 定义parameter and return
# 函数作为列表元素
# [ ]用做index,因为()要声明函数,传入参数
many_fucntion=[
(lambda x: x**2), # list 用“,”隔开
(lambda x: x**3)]
print(many_fucntion[0](2),many_fucntion[1](2))
fliter function
# The filter() function in Python
# takes in a function and a list as
# arguments.
# The function is called with all the
# items in the list and a new list
# returned which contains items in
# the list and a new list is returned
# which contains items for which
# the function evaluats to True.
my_list=[1,5,4,6,11,3,12]
new_list=list(filter((lambda x : x%2==0),my_list))
# Output :[4,6,12]
new_list
[i for i in my_list if i%2==0] # list comprehension
map (矩阵操作)
items=list(range(1,6))
squared=list(map((lambda x :x**2),items))
squared
def fahrenheit(T):
return ((float(9)/5)*T+32)
def celsius(T):
return (float(5)/9*(T-32))
temp=[36.5,37,37.5,39]
F=map(fahrenheit,temp)
list(F)
---
# 传入多个函数
def multiply(x):
return (x*x)
def add(x):
return (x+x)
func=[add, multiply]
for i in range(5):
print(i)
value=list(map((lambda x: x(i)),func))
print(value)
reduce
# Reduce 遍历操作
from functools import reduce
reduce((lambda x,y:x+y),[47,11,42,13])
# 找出最小值
f=lambda a,b:a if (a>b) else b
reduce(f,[47,11,42,102,13])
# sum from 1 to 100
reduce((lambda x,y:x+y),range(1,101))
generators
%magic 调用magic function
%magic
之后的代码是之前基础的叠加。
exception——目的是,出现错误让程序继续运行。
a=0
try:
1/0 # 产生异常,没有停止运行,而是做了什么。
# except:
except ZeroDivisionError :
print("zeros") # 每个异常都有固定的名字
print("error")
程序员永远都是最懒的(防止盖起来复杂)
def extract_hero_img(current_page):
start_link=page_hero.find('src="') #找到一个固定的特征,帮助确定位置
start_quote=page_hero.find('"',start_link)
end_quote=page_hero.find('"',start_quote+1)
end_bracker=page_hero.find('>',end_quote)
end_bracker
start_bracker=page_hero.find('<',end_bracker+1)
start_bracker
print(page_hero[start_quote+1:end_quote])
print(page_hero[end_bracker+1:start_bracker])
return start_bracker
# 调用函数
entry_xuance=extract_hero_img(page_hero)
page_hero=page_hero[entry_xuance:]
extract_hero_img(page_hero)
使用循环注意:跳出的条件。
page_hero='''<ul class="herolist clearfix">
<li><a href="herodetail/506.shtml" target="_blank"><img
src="//game.gtimg.cn/images/yxzj/img201606/heroimg/506/506.jpg" width="91"
height="91" alt="云中君">云中君</a></li>
<li><a href="herodetail/505.shtml" target="_blank"><img
src="//game.gtimg.cn/images/yxzj/img201606/heroimg/505/505.jpg" width="91"
height="91" alt="瑶">瑶</a></li>
src="//game.gtimg.cn/images/yxzj/img201606/heroimg/105/105.jpg" width="91"
height="91" alt="廉颇">廉颇</a></li></ul>'''
start_index=0
last_index=0
def extract_hero_img(current_page):
start_link=page_hero.find('src="') #找到一个固定的特征,帮助确定位置
start_quote=page_hero.find('"',start_link)
end_quote=page_hero.find('"',start_quote+1)
end_bracker=page_hero.find('>',end_quote)
start_bracker=page_hero.find('<',end_bracker+1)
if current_page[start_quote+1:end_quote].startswith("//"):
print(page_hero[start_quote+1:end_quote])
print(page_hero[end_bracker+1:start_bracker])
return start_bracker
else :
return -1
---
while True:
page_hero=page_hero[last_index:]
last_index=extract_hero_img(page_hero)
if last_index==-1:
break
小结:重复的东西函数化,多次用循环
quize code structure
# Define constant variables.
BATE=5.0
INITIAL_BALANCE=180000
addiation=24000
# Print the table of balance for each year.
banlance=INITIAL_BALANCE
bal_recores=[]
# your solution below
for i in range(1,21):
total_each=(banlance+addiation)*(1+BATE/100)
# print(total_each)
bal_recores.append(total_each)
interest=(banlance+addiation)*(BATE/100)
banlance=total_each
# print("{} {}".format(i,total_each))
# print("year:{}. total:{}, interest:{}".format(i,total_each,interest))
# print("year:{},intest:{},balance:{}".format(i,interest,total_each))
print("year:%4d, intest: %10.2f, balance:%10.2f" %(i,interest,total_each))
# plot figure
import matplotlib.pyplot as plt
fig, ax=plt.subplots()
ax.plot([i for i in range(1,20+1)],list(map((lambda x: x/1e4),bal_recores)))
ax.set(xlabel='n th year',ylabel='Money wan',title='How much I got')
ax.grid()
plt.show()
网友评论