10python-函数

函数一

def function():
    函数体
    ...
    
function()

发邮件

# 邮件库
import smtplib
# 加密
from smtplib import SMTP_SSL
#邮件正文
from email.mime.text import MIMEText
# 邮件主体
from email.mime.multipart import MIMEMultipart
# 邮件头
from email.header import Header


def send_email(email):
    # ### 1.邮件内容配置 ###
    # 参数
    my_server = 'smtp.189.cn'
    my_mail = "发件人邮箱名@189.cn"
    my_pwd = "发件人邮箱密码"

    send_title = "python send mail automatically"
    mail_content = "this is my test mail by python"

    mail_body = MIMEMultipart()
    mail_body['Subject'] = Header(send_title,'utf-8')
    mail_body['From'] = Header(my_mail,'utf-8')
    mail_body['To'] = Header('test by python','utf-8')
    mail_body.attach(MIMEText(mail_content,'plain','utf-8'))

    smtp = SMTP_SSL(my_server)
    smtp.login(my_mail,my_pwd)
    smtp.sendmail(my_mail,email,mail_body.as_string())
    smtp.quit()

mail_address = "收件人的邮箱名@qq.com"
send_email(mail_address)

函数参数


位置传参

def func(n1,n2):
	print(n1+n2)
func(13,12)

关键字传参

def func(n1,n2):
    print(n1+n2)
    
func(n1=11,n2=2)
# 位置和关键参数混用,关键字参数要在前面)
func(112, 8, a3=7)
func(112, a2=8, a3=7)
func(a1=112, a2=8, a3=7)

动态参数及注意事项

def my_function(*args):
    print(args) # 接收的变量相当于元组 (1,2,)
# 只能按照位置传参
my_function(22,33,99)
# 为空的时候相当于接收空元组
my_function()


def my_function(**kwargs):
    print(kwargs)  # 接收的变量相当于字典{"name":"武大","age":"36","feature":"小"}  {}

# 只能按关键字传参
my_function(name="武大", age=36, feature="小")

def my_function(*args,**kwargs):
    print(args,kwargs) # (1,2,3) {}

my_function(1,2,3,name="武大", age=36,)
my_function() #接收的是代元组+字典

# * 必须放在 ** 的前面
def my_function(*args, **kwargs):
    print(args, **kwargs)

# 动态参数只能放在一般参数的最后。
def my_function(n1, n2, n3, *args, **kwargs):
    print(n1, n2, n3, args, **kwargs)

# 默认值参数放在**关键字参数前面
def my_function(n1, n2, n3, n4=10, *args, n5=20, **kwargs):
    print(n1, n2, n3, n4, n5, args, kwargs)

my_function(1, 2, 3, 4, 5, 6, 7, n5=100, n10=778)

函数返回值

  1. 返回值能是任意类型,如果函数中没写return,或写了return但没有赋值,则返回值都是None。
  2. 函数一旦遇到return就会立即退出函数(终止函数中的所有代码)
def my_function():
    total = 1 + 1

result = my_function()
print(result)  # None

def my_function():
    total = 1 + 1
    return  # 或 return None

result = my_function()
print(result) # None

# 返回值后有逗号,则会将返回值转换成元组返回
def my_function():
    return 1,2,3

total = my_function()
print(total) # (1,2,3)

你可能感兴趣的:(python,python,开发语言)