table of Contents
Process-oriented programming with a programming function
Up to now we have contacted, program written for: process-oriented programming [poor readability / reusability poor]
# 面向过程编程
user_input = input('请输入角色:')
if user_input == '管理员':
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('管理员,我想演男一号,你想怎么着都行。', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["管理员", '[email protected]'])
msg['Subject'] = "情爱的导演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['管理员', ], msg.as_string())
server.quit()
elif user_input == '业务员':
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('业务员,我想演男一号,你想怎么着都行。', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["业务员", '业务员'])
msg['Subject'] = "情爱的导演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['业务员', ], msg.as_string())
server.quit()
elif user_input == '老板':
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('老板,我想演男一号,你想怎么着都行。', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["老板", '老板邮箱'])
msg['Subject'] = "情爱的导演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['老板邮箱', ], msg.as_string())
server.quit()
# 函数式编程
def send_email():
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('老板,我想演男一号,你想怎么着都行。', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["老板", '老板邮箱'])
msg['Subject'] = "情爱的导演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['老板邮箱', ], msg.as_string())
server.quit()
user_input = input('请输入角色:')
if user_input == '管理员':
send_email()
elif user_input == '业务员':
send_email()
elif user_input == '老板':
send_email()
For functional programming:
- Nature: the N lines of code to get away and gave him a name, can be found later by name and code execution.
- Scenes:
- Repeat Code
- Code particularly more than one screen may be selected by the function code divided
The basic structure function 2
# 函数的定义
def 函数名(): # 函数名的命名规范、建议与变量的一样
# 函数内容 (缩进)
pass
# 函数的执行
函数名()
def get_list_first_data():
v = [11,22,33,44]
print(v[0])
get_list_first_data()
# 注意:函数如果不被调用,则内部代码永远不会被执行。
# 假如:管理员/业务员/老板用的是同一个邮箱。
def send_email():
print('发送邮件成功,假设有10含代码')
user_input = input('请输入角色:')
if user_input == '管理员':
send_email()
elif user_input == '业务员':
send_email()
elif user_input == '老板':
send_email()
to sum up:
# 情况1
def f1():
pass
f1()
# 情况2
def f2(a1):
pass
f2(123)
# 情况3
def f3():
return 1
v1 = f3()
# 情况4
def f4(a1,a2):
# ...
return 999
v2 = f4(1,7)
def show(name,age):
"""
函数是干什么的... # 必须注明函数
:param name:
:param age:
:return:
"""
return None
Whether the data inside the function will be executed independently of each other confusion between the function and the function :()
- 1. The function is finished
- 2. Internal element is not used by another person ----> destroy the function performed by the amount of memory
Parameter 3 Functions
def get_list_first_data(aaa): # aaa叫形式参数(形参)
v = [11,22,33,44]
print(v[aaa])
get_list_first_data(1) # 2/2/1调用函数时传递叫:实际参数(实参)
get_list_first_data(2)
get_list_first_data(3)
get_list_first_data(0)
The exact order transmission parameters: parameter passing mode position
The actual parameters may be any type
# 假如:管理员/业务员/老板用的是同一个邮箱。
"""
def send_email(to):
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('导演,我想演男一号,你想怎么着都行。', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["导演", to])
msg['Subject'] = "情爱的导演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', [to, ], msg.as_string())
server.quit()
"""
def send_email(to):
template = "要给%s发送邮件" %(to,)
print(template)
user_input = input('请输入角色:')
if user_input == '管理员':
send_email('[email protected]')
elif user_input == '业务员':
send_email('[email protected]')
elif user_input == '老板':
send_email('[email protected]')
Exercises
# 1. 请写一个函数,函数计算列表 info = [11,22,33,44,55] 中所有元素的和。
def get_sum():
info = [11,22,33,44,55]
data = 0
for item in info:
data += item
print(data)
get_sum()
# 2. 请写一个函数,函数计算列表中所有元素的和。
def get_list_sum(a1):
data = 0
for item in a1:
data += item
print(data)
get_list_sum([11,22,33])
get_list_sum([99,77,66])
v1 = [8712,123,123]
get_list_sum(v1)
# 3. 请写一个函数,函数将两个列表拼接起来。
def join_list(a1,a2):
result = []
result.extend(a1)
result.extend(a2)
print(result)
join_list([11,22,33],[55,66,77]
# 4. 计算一个列表的长度
def my_len(arg):
count = 0
for item in arg:
count += 1
print(count)
v = [11,22,33]
my_len(v)
len(v)
# 5. 发邮件的示例
def send_email(role,to):
template = "要给%s%s发送邮件" %(role,to,)
print(template)
user_input = input('请输入角色:')
if user_input == '管理员':
send_email('管理员','[email protected]')
elif user_input == '业务员':
send_email('业务员','[email protected]')
elif user_input == '老板':
send_email('老板','[email protected]')
3.1 Katachisan
3.1.1 The basic parameters of knowledge
It can be any number of parameters
It can be any type
def func(a1,a2,a3,a4): print(a1,a2,a3,a4) func(2,'name',[1,2,3],False)
3.1.2 default parameters
def func(a1,a2,a3=9,a4=10): # 默认参数a3=9,a4=10
print(a1,a2,a3,a4)
func(11,22) # 不给a3,a4传值,则a3,a4等于默认参数
func(11,22,10)
func(11,22,10,100)
func(11,22,10,a4=100)
func(11,22,a3=10,a4=100)
func(11,a2=22,a3=10,a4=100)
func(a1=11,a2=22,a3=10,a4=100)
3.1.3 universal parameter (for break)
*args
Receiving position can be any number of arguments, and the parameters into tuples.
1. Call function None *
def func(*args): print(*args) func(1,2) ==> (1,2) func(1,2,[12,3,4]) ==> (1,2,[12,3,4]) func((11,22,33)) ==> ((11,22,33)) # 参数是一个元组,打印出来的效果是元组套元组。
2. The calling function *
def func(*args): print(args) func(*(11,22,33)) ==>(11,22,33) # *是用来打散元组的,将元组中的每个元素作为参数。 func(*[11,22,33]) ==>(11,22,33) # *可以用来打散列表/元组 /字典/集合,只是循环内部元素
3. The only parameter passing by position
def func(*args): print(args) func(1) func(1,2) # args=(1, 2) func((11,22,33,44,55)) # args=((11,22,33,44,55),) func(*(11,22,33,44,55)) # args=(11,22,33,44,55)
** kwargs
Keywords can accept any number of arguments, and see the conversion parameters into a dictionary
1. Call function None *
def func(**kwargs): print(***kwargs) func(k=1) **kwargs = {'k':1} func(k1=1,k2=3) **kwargs = {'k1':1,'k2':3}
2. The calling function *
def func(**kwargs): print(kwargs) func(**{'k1':1,'k2':4,'k3':9}) **kwargs = {'k1':1,'k2':4,'k3':9}
3. Use keywords can only pass parameters
* Args / ** kwargs integrated use: Invincible Invincible + => true invincible
def func(*args,**kwargs): print(args,kwargs) func(1,2,3,4,5,k1=2,k5=9,k19=999) *arg = (1,2,3,4,5) **kwargs = {'k1':2,'k5':9,'k19':999} func(*[1,2,3],k1=2,k5=9,k19=999) *arg = (1,2,3) **kwargs = {'k1':2,'k5':9,'k19':999} func(*[1,2,3],**{'k1':1,'k2':3}) *arg = (1,2,3) **kwargs = {'k1':1,'k2':3} func(111,222,*[1,2,3],k11='alex',**{'k1':1,'k2':3}) *arg = (111,222,1,2,3) **kwargs = {'k11':'alex','k1':1,'k2':3}
3.2 arguments
3.2.1 Location pass parameters (call the function and pass parameters) (execution)
Call / time function is executed strictly in the order position of the incoming parameters
def func(a1,a2,a3):
print(a1,a2,a3)
func(66,'alex',3)
3.2.2 key parameter passing (execution)
The key parameter is the parameter passing arguments to put to use in
def func(a1,a2):
print(a1,a2)
func(a1=22,a2=8)
Pass pass parameters involved in key positions can be used in combination: the parameters to be passed in a position on the front, to be placed behind the key parameter passing, and finally equal to the total number of parameters
def func(a1,a2,a3):
print(a1,a2,a3)
func(1,2,a3=3)
func(1,a2=2,a3=3)
func(a1=1,a2=2,a3=3)
func(a1=1,2,3) # 是错误的
def func (): Custom open () function of the two built-in functions for python
matching len ()
3.3 Key parameters related to
Defined Functions
def func(a1,a2): pass def func(a1,a2=None): # 对于默认值,不可变类型随便写,如果是可变类型(有坑)。 pass def func(*args,**kwargs): pass
For general use the default value of the function immutable type, variable type caution:
If you want to set the default value is the empty list:
# 不推荐使用(会有坑): def func(data,value = []) pass 推荐使用: def func(data ,value = None) if not value: value = []
# 示例: def func(data,value = [] value.append(data) return value v1 = func(1) # v1 = [1] v2 = func(2,[11,22,33]) # v2 = [11,22,33,2] v3 = func(3) # v3 = [1,3]
Exercises:
def func (a, b = []) What trap?
If you do not pass to the b parameter, the default is the same address
Look at the code written results
def func(a,b=[]): b.append(a) return b l1 = func(1) l2 = func(2,[11,22]) l3 = func(3) print(l1,l2,l3) # [1,3] [11,22,2] [1,3]
Look at the code written results
def func(a,b=[]): b.append(a) print(b) func(1) # [1] func(2,[11,22,33]) # [11,22,33,2] func(3) # [1,3]
call function
Front position parameter, the parameter after the keyword.