函数、全局变量、局部变量

1 #定义函数
2 def xx():
3     print('free')
4 def oo():
5     print('free')
6 #调用函数
7 xx()
8 oo()
  1. 函数返回值

          默认返回 None 

1 def email():
2     print('eee')
3     return '123'
4 ret = email()
5 print(ret)

 

2.函数的 普通参数 . 函数的传参,传的是引用。

1 def kuaidi(p):
2     print(p)
3 
4     return True
5 
6 
7 ret = kuaidi('13824562647')
8 if ret:
9     print('success')

函数实例:发邮件

 1 def email(p,text,subject):
 2     import smtplib
 3     from email.mime.text import MIMEText
 4     from email.utils import formataddr
 5     ret = True
 6     try:
 7         msg = MIMEText(text,'plain','utf-8')
 8         msg['From'] =  formataddr(['深圳市','wptawy@126'])
 9         msg['To'] = formataddr(['走人','1039296479@qq.com'])
10         msg['Subject'] = subject
11 
12 
13         server = smtplib.SMTP('smtp.126.com',25)
14         server.login('wptawy@126.com','WW.3945.59')
15         server.sendmail('wptawy@126.com',[p,],msg.as_string())
16         server.quit()
17     except:
18         ret = False
19     return ret
20 rr =  email('1039296479@qq.com','text','subject')
21 if rr:
22     print('seccuss')
23 else:

 函数执行到return  退出函数

函数的指定参数:

形参,实参(默认,按照顺序传)

指定形参传入实参,可以不按照顺序 

 

函数的默认值:

函数可以有默认参数

def drive(name='chenzhigong'): #设置默认值,有默认参数的形参要放到后面,否则会报错。
temp = name + '123'
return temp

ret = drive()
print(ret)

函数的动态参数(一):

  1. def f1(*a): #前面加一个*号
    print(a,type(a))

    f1(123,456,[11,33])

函数的动态参数(二)

  1. def f1(**a): #前面加两个*号
    print(a,type(a))

    f1(k1=123,k2=456)#传入值时必须以键值对方式传入

    H:\python\venv\Scripts\python.exe E:/pyhton/s18.py
    {'k1': 123, 'k2': 456} <class 'dict'> 函数的动态参数二,两个星号,传输过去后输出成字典。函数的动态参数一,传输过去后输出成元组。

    Process finished with exit code 0

  2. def f1(*a,**aa):
    print(a,type(a))

    print(aa,type(aa))
    f1(11,22,k1=123,k2=456)

    H:\python\venv\Scripts\python.exe E:/pyhton/s18.py
    (11, 22) <class 'tuple'>
    {'k1': 123, 'k2': 456} <class 'dict'>

    Process finished with exit code 0

  3. def f1(*args):
    print(args,type(args))

    li = [11,22,33]
    f1(li)
    f1(*li)

    H:\python\venv\Scripts\python.exe E:/pyhton/s18.py
    ([11, 22, 33],) <class 'tuple'>
    (11, 22, 33) <class 'tuple'>

    Process finished with exit code 0

  4. def f1(**kargs):
    print(kargs,type(kargs))

    li = {'k1':123}
    f1(k1=li)
    f1(**li)

    H:\python\venv\Scripts\python.exe E:/pyhton/s18.py
    {'k1': {'k1': 123}} <class 'dict'>
    {'k1': 123} <class 'dict'>

    Process finished with exit code 0

  5. global 变量  ————》修改全局变量。全局变量都大写,局部变量都小写。
posted @ 2019-06-05 19:43  Freechen0  阅读(117)  评论(0)    收藏  举报