Python--函数

一、函数定义:
 1.在一个变化过程中,如果有两个变量x和y,并且对于x的每一个确定的值,y都有唯一确定的值与其对应,那么我们就把x成为自变量,y成为因变量,y是x的函数。
 自变量x的取值范围叫做这个函数的定义域
 2.在编程语言中,函数是逻辑结构化和过程化的一种编程方法。

  python中函数的定义方法:

def test(x):
    "The function definitions"  
    x += 1
    return x   #在函数中,return一般放在最后,一旦执行到return,函数即终止

  def:定义函数的关键字  test:函数名  (x):参数  x:返回值

 定义过程:过程没有return返回

def func2():
    '''testing2'''
    print('in the func2')


 

  执行:

def func1():
"""testing1"""
print('in the func1')
return 0


def func2():
    '''testing2'''
    print('in the func2')

x = func1()
y = func2()

print('x',x)
print('y',y)
>>>
in the func1
in the func2
x 0
y None

  过程因为没有返回值,所以y的值是None

  模拟一个写日志的小程序:

def lgwr(): #定义一个写日志的过程
    with open('a.txt','a') as f:
        f.write('
end action')
#下面3个过程都分别调用写日志的过程。
import time
def lgwr():
    time_format = '%Y-%m-%d %X'  #定义时间格式
    time_current = time.strftime(time_format) #定义变量为当前时间
    with open('a.txt','a') as f:
        f.write('time %s end action
' %time_current)

def test1():
    print('in the test1')
    lgwr()


def test2():
    print('in the test2')
    lgwr()

def test3():
    print('in the test3')
    lgwr()

test1()
test2()
test3()

  普通参数:使用定义函数来完成发送邮件

def sendmail(mailaddr,content):
    try:
        import smtplib
        from email.mime.text import MIMEText
        from email.utils import formataddr

        msg = MIMEText(content,'plain','utf-8')  #邮件内容
        msg['From'] = formataddr(['Tim','aqing1243@163.com'])
        msg['To'] = formataddr(['走人','51828446@qq.com'])
        msg['Subject'] = '主题'

        server = smtplib.SMTP('smtp.163.com',25)
        server.login('aqing1243@163.com','sina4433') #发送方邮箱账户密码
        server.sendmail('aqing1243@163.com',[mailaddr,],msg.as_string()) #目标端邮箱
        server.quit()
    except:
        return False  #发送失败执行
    else:
        return True  #发送成功执行

while True:
    em = input('请输入邮箱:')
    text = input('请输入内容:')
    result = sendmail(em,text)
    if result == True:
        print("发送成功")
        break
    else:
        print('发送失败')

函数的参数传递按照形参的顺序依次传递,一般有几个形参,在调用函数时就需要传递几个参数。
 如果函数有默认参数的情况下,默认函数可以不传递。默认函数一般放在最后。
 

  默认参数:

def send(name,content,xx='OK')
...
...
return ....

send('Tim','hello') #第三个默认参数可以不传递,不传递的时候函数使用默认值
send('Tim','hello','good')

  指定参数:

ef send(name,content)
    ...
    ...
    return ....

send(content='hello',name='Tim') #参数也可以不按照顺序传递,但是需要指定形参的赋值
send('Tim','hello')    

  

  动态参数1:

def f1(*args):  #动态参数加*表明,默认将传入参数放置在元组中
    print(args,type(args))
f1(11,22,'Tim','hhhh') #将每个参数添加进元组作为一个元素
li = [11,22,'Tim','hhhh']
f1(*li)  #将列表的元素转化为元组的元素
f1(li) #将列表当成一个元素传给元组
>>>
(11, 22, 'Tim', 'hhhh') <class 'tuple'>
(11, 22, 'Tim', 'hhhh') <class 'tuple'>
([11, 22, 'Tim', 'hhhh'],) <class 'tuple'>


    动态参数2**def f1(**args):  #动态参数加**表明,默认将传入参数放置在字典中
    print(args,type(args))
f1(k1="v1",k2='v2') #传递字典的形式
dic = {'k1':'v1','k2':'v2'}
f1(**dic) #把字典的每一个元素传递给字典
>>>
{'k2': 'v2', 'k1': 'v1'} <class 'dict'>
{'k1': 'v1', 'k2': 'v2'} <class 'dict'>

 

  万能参数:

def f1(*args,**kwargs):  #*在前,**在后
    print(args)
    print(kwargs)
f1(11,22,33,44,k1='v1',k2='v2')
>>>
(11, 22, 33, 44)
{'k2': 'v2', 'k1': 'v1'}

 

  format()的各种参数使用:

s = 'i am {0},age {1}'.format('Tim',18)
s1 = 'i am {0},age {1}'.format(*['Tim',18])
s2 = 'i am {name},age {age}'.format(name='Tim',age=18)

dic = {'name':'Tim','age':18}
s3 = 'i am {name},age {age}'.format(**dic)

print(s)
print(s1)
print(s2)
print(s3)
>>>
i am Tim,age 18
i am Tim,age 18
i am Tim,age 18
i am Tim,age 18

 

  引用参数:函数内部运算的结果直接作用于外部的参数变量。

def f1(a1):
    a1.append(999)

li = [11,22,33,44]
f1(li)
print(li)
>>>
[11, 22, 33, 44, 999]

  

name = ['Tim','mike'] #全局变量
name1 = ['Eric','Jeson'] #全局变量
name3 = ['Tom','jane'] #全局变量

def f1():
    name.append('Eric') #列表的append方法可改变外部全局变量的值
    print('函数内name: %s'%name)
    name1 = '123' #重新赋值不可改变外部全局变量的值
    print('函数内name1: %s'%name1)
    global name3 #如果需要重新给列表赋值,需要使用global定义全局变量
    name3 = '123'
    print('函数内name3: %s'%name3)
f1()
print('函数外name: %s'%name)
print('函数外name1: %s'%name1)
print('函数外name3: %s'%name3)
>>>
函数内name: ['Tim', 'mike', 'Eric']
函数内name1: 123
函数内name3: 123
函数外name: ['Tim', 'mike', 'Eric']
函数外name1: ['Eric', 'Jeson']
函数外name3: 123
原文地址:https://www.cnblogs.com/guqing/p/6110911.html