zoukankan      html  css  js  c++  java
  • day_3

    函数

    • 函数可以用来定义可重复代码,组织和简化
    • 一般来说一个函数在实际开发中为一个小功能
    • 一个类为一个大功能
    • 同样函数的长度不要超过一屏
     

    Python中的所有函数实际上都是有返回值(return None),

    如果你没有设置return,那么Python将不显示None.

    如果你设置return,那么将返回出return这个值.

    In [29]:
     
     
     
     
     
    def HJN():
        print('Hello')
        return 1000
     
     
    In [30]:
     
     
     
     
     
    b=HJN()
    print(b)
     
     
     
    Hello
    1000
    
    In [3]:
     
     
     
     
     
    HJN
     
     
    Out[3]:
    <function __main__.HJN()>
    In [10]:
     
     
     
     
     
    def panduan(number):
        if number % 2 == 0:
            print('O')
        else:
            print('J')
     
     
    In [13]:
     
     
     
     
     
    panduan(number=1)
     
     
     
    J
    
    In [12]:
     
     
     
     
     
    panduan(2)
     
     
     
    O
    
     

    定义一个函数

    def function_name(list of parameters):

    do something

    • 以前使用的random 或者range 或者print.. 其实都是函数或者类
     

    函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.

    In [31]:
     
     
     
     
     
    import random
     
     
    In [ ]:
     
     
     
     
     
    def hahah():
        n = random.randint(0,5)
        while 1:
            N = eval(input('>>'))
            if n == N:
                print('smart')
                break
            elif n < N:
                print('太小了')
            elif n > N:
                print('太大了')
     
     
     

    调用一个函数

    • functionName()
    • "()" 就代表调用
    In [1]:
     
     
     
     
     
    def H():
        print('hahaha')
     
     
    In [2]:
     
     
     
     
     
    def B():
        H()
     
     
    In [3]:
     
     
     
     
     
    B()
     
     
     
    hahaha
    
    In [4]:
     
     
     
     
     
    def A(f):
        f()
     
     
    In [5]:
     
     
     
     
     
    A(B)
     
     
     
    hahaha
    
     

     

    带返回值和不带返回值的函数

    • return 返回的内容
    • return 返回多个值
    • 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
     

    • 当然也可以自定义返回None
     

    EP:

    In [8]:
     
     
     
     
     
    def main():
        print(min(min(5,6),(51,6)))
    def min(n1,n2):
        a = n1
        if n2 < a:
            a = n2
     
     
    In [9]:
     
     
     
     
     
    main()
     
     
     
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-9-263240bbee7e> in <module>
    ----> 1 main()
    
    <ipython-input-8-a7c84f32bfda> in main()
          1 def main():
    ----> 2     print(min(min(5,6),(51,6)))
          3 def min(n1,n2):
          4     a = n1
          5     if n2 < a:
    
    <ipython-input-8-a7c84f32bfda> in min(n1, n2)
          3 def min(n1,n2):
          4     a = n1
    ----> 5     if n2 < a:
          6         a = n2
    
    TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
    
    
     

    类型和关键字参数

    • 普通参数
    • 多个参数
    • 默认值参数
    • 不定长参数
     

    普通参数

     

    多个参数

     

    默认值参数

     

    强制命名

    In [60]:
     
     
     
     
     
    def U(str_):
        xiaoxie = 0
        for i in str_:
            ASCII = ord(i)
            if 97<=ASCII<=122:
                xiaoxie +=1
            elif xxxx:
                daxie += 1
            elif xxxx:
                shuzi += 1
        return xiaoxie,daxie,shuzi
     
     
    In [61]:
     
     
     
     
     
    U('HJi12')
     
     
     
    H
    J
    i
    1
    2
    
     

    不定长参数

    • *args
      • 不定长,来多少装多少,不装也是可以的
      • 返回的数据类型是元组
      • args 名字是可以修改的,只是我们约定俗成的是args
    • **kwargs
      • 返回的字典
      • 输入的一定要是表达式(键值对)
    • name,*args,name2,**kwargs 使用参数名
    In [ ]:
     
     
     
     
     
    def TT(a,b)
     
     
    In [51]:
     
     
     
     
     
    def TT(*args,**kwargs):
        print(kwargs)
        print(args)
    TT(1,2,3,4,6,a=100,b=1000)
     
     
     
    {'a': 100, 'b': 1000}
    (1, 2, 3, 4, 6)
    
    In [13]:
     
     
     
     
     
    {'key':'value'}
     
     
     
    ()
    
    In [14]:
     
     
     
     
     
    TT(1,2,4,5,7,8,9,)
     
     
     
    (1, 2, 4, 5, 7, 8, 9)
    
    In [38]:
     
     
     
     
     
    def B(name1,nam3):
        pass
     
     
    In [39]:
     
     
     
     
     
    B(name1=100,2)
     
     
     
      File "<ipython-input-39-bd6a38e58465>", line 1
        B(name1=100,2)
                   ^
    SyntaxError: positional argument follows keyword argument
    
    
    
    In [43]:
     
     
     
     
     
    def sum_(*args,A='sum'):
    
    
        res = 0
        count = 0
        for i in args:
            res +=i
            count += 1
        if A == "sum":
            return res
        elif A == "mean":
            mean = res / count
            return res,mean
        else:
            print(A,'还未开放')
    
    
    
    
     
     
    In [46]:
     
     
     
     
     
    sum_(-1,0,1,4,A='var')
     
     
     
    var 还未开放
    
    In [ ]:
     
     
     
     
     
    'aHbK134'.__iter__
     
     
    In [48]:
     
     
     
     
     
    b = 'asdkjfh'
    for i in b :
        print(i)
     
     
     
    a
    s
    d
    k
    j
    f
    h
    
    In [ ]:
     
     
     
     
     
    2,5
    2 + 22 + 222 + 2222 + 22222
     
     
     

    变量的作用域

    • 局部变量 local
    • 全局变量 global
    • globals 函数返回一个全局变量的字典,包括所有导入的变量
    • locals() 函数会以字典类型返回当前位置的全部局部变量。
    In [54]:
     
     
     
     
     
    a = 1000
    b = 10
    def Y():
        global a,b
        a += 100
        print(a)
    Y()
     
     
     
    1100
    
    In [55]:
     
     
     
     
     
    def YY(a1):
        a1 += 100
        print(a1)
    YY(a)
    print(a)
     
     
     
    1200
    1100
    
     

    注意:

    • global :在进行赋值操作的时候需要声明
    • 官方解释:This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
     

    Homework

    • 1
    In [13]:
     
     
     
     
     
    def getPentagonalNumber(n):
            c = 0
            for i in range(1,n+1):
                    he = int((i*(3*i - 1))/2)
                    print(he,end=' ')
                    c += 1
                    if c % 10 == 0:
                            print()
    getPentagonalNumber(100)  
    
    
    
    
     
     
     
    1 5 12 22 35 51 70 92 117 145 
    176 210 247 287 330 376 425 477 532 590 
    651 715 782 852 925 1001 1080 1162 1247 1335 
    1426 1520 1617 1717 1820 1926 2035 2147 2262 2380 
    2501 2625 2752 2882 3015 3151 3290 3432 3577 3725 
    3876 4030 4187 4347 4510 4676 4845 5017 5192 5370 
    5551 5735 5922 6112 6305 6501 6700 6902 7107 7315 
    7526 7740 7957 8177 8400 8626 8855 9087 9322 9560 
    9801 10045 10292 10542 10795 11051 11310 11572 11837 12105 
    12376 12650 12927 13207 13490 13776 14065 14357 14652 14950 
    
     
    • 2
    In [18]:
     
     
     
     
     
    def sumDigits(i):
    
    
        ge=i%10
        shi=i//10%10
        bai=i//100
        sum=ge + shi +bai
        print(sum)
    
    
    sumDigits(234)
    
    
     
     
     
    9
    
     
    • 3
    In [23]:
     
     
     
     
     
    def displaySortedNumbers(num1,num2,num3):
            shu = [num1,num2,num3]
            shen = sorted(shu)
            for i in range(len(shu)):
                  print(shen[i],end=" ")
    num1,num2,num3 = map(float,input('Enter three number: ').split(','))
    displaySortedNumbers(num1,num2,num3)
    
    
    
    
    
    
     
     
     
    Enter three number: 1,16,15
    1.0 15.0 16.0 
     
    • 4
    In [81]:
     
     
     
     
     
    def futureInvestmenValue(investmentAmount,monthlyInterestRate,years):
        for years in range(1,years):
            investmentAmount = float(investmentAmount+investmentAmount*monthlyInterestRate)
            print('%d            %.2f'%(years,investmentAmount))
    investmentAmount = float(input('The amount invested: '))
    monthlyInterestRate = float(input('Annual interest rate: '))*0.01
    print('years    Future Value')
    futureInvestmenValue(investmentAmount,monthlyInterestRate,31)
     
     
     
    The amount invested: 1000
    Annual interest rate: 9
    years    Future Value
    1            1090.00
    2            1188.10
    3            1295.03
    4            1411.58
    5            1538.62
    6            1677.10
    7            1828.04
    8            1992.56
    9            2171.89
    10            2367.36
    11            2580.43
    12            2812.66
    13            3065.80
    14            3341.73
    15            3642.48
    16            3970.31
    17            4327.63
    18            4717.12
    19            5141.66
    20            5604.41
    21            6108.81
    22            6658.60
    23            7257.87
    24            7911.08
    25            8623.08
    26            9399.16
    27            10245.08
    28            11167.14
    29            12172.18
    30            13267.68
    
     
    • 5
    In [80]:
     
     
     
     
     
    def printChars(ch1,ch2):
        count=0
        zimu=0
        for i in range(1,ch1):
            print(i,end=' ')
            count +=1
        for j in range(ord('A'),ch2+1):    
            print(chr(j),end=' ')
            zimu+=1
            sum=count+zimu
            if sum%10==0:
                print('\n')
    printChars(10,ord('Z'))
    
    
     
     
     
    1 2 3 4 5 6 7 8 9 A 
    
    B C D E F G H I J K 
    
    L M N O P Q R S T U 
    
    V W X Y Z 
     
    • 6
    In [82]:
     
     
     
     
     
    def numberOfDaysInAYear(year):
        for year in range(2010,year):
            if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
                print('%d年有366天'%year)
            else:
                print('%d年有365天'%year)
    
    
    numberOfDaysInAYear(2021)
     
     
     
    2010年有365天
    2011年有365天
    2012年有366天
    2013年有365天
    2014年有365天
    2015年有365天
    2016年有366天
    2017年有365天
    2018年有365天
    2019年有365天
    2020年有366天
    
     
    • 7
    In [83]:
     
     
     
     
     
    import math
    def distance(x1,y1,x2,y2):
        sum1 = (x1-x2) ** 2
        sum2 = (y1-y2) ** 2
        sum3 = math.sqrt(sum1 + sum2)
        print(sum3)
    x1 = int(input('x1= '))
    x2 = int(input('x2= '))
    y1 = int(input('y1= '))
    y2 = int(input('y2= '))
    distance(x1,y1,x2,y2)
     
     
     
    x1= 2
    x2= 3
    y1= 4
    y2= 5
    1.4142135623730951
    
     
    • 8
    In [84]:
     
     
     
     
     
    print('p      2^p - 1')
    def sushu():
        for i in range(2,32):
            for j in range(2,i):
                if i % j == 0:
                    break
            else: 
                for k in range(i+1):
                        if (2 ** k) - 1 == i:
                                print('%d        %d'%(k,i))
    sushu()
     
     
     
    p      2^p - 1
    2        3
    3        7
    5        31
    
     
    • 9
    In [1]:
     
     
     
     
     
    import time
     
     
    In [13]:
     
     
     
     
     
    import time
    localtime = time.asctime(time.localtime(time.time()))
    print("本地时间为 :", localtime)
     
     
     
    本地时间为 : Sat May 11 08:37:21 2019
    
    In [9]:
     
     
     
     
     
    2019 - 1970
     
     
    Out[9]:
    49
    In [ ]:
     
     
     
     
     
     
     
     
    • 10
    In [85]:
     
     
     
     
     
    import random
    x1 = random.randrange(1,7)
    x2 = random.randrange(1,7)
    sum = x1 + x2
    def dubo():
            if sum in [2,3,7,11,12]:
                    if sum in [2,3,12]:
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You lose')
                    else: 
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You win')
            if sum in [4,5,6,8,9,10]:
                    print('You rolled %d + %d = %d'%(x1,x2,sum))
                    print('point is %d'%sum)
                    y1 = random.randrange(1,7)
                    y2 = random.randrange(1,7)
                    sum2 = y1 + y2
                    if sum2 != sum:
                            print('You rolled %d + %d = %d'%(x1,x2,sum2))
                            print('You lose')
                    elif sum2 == sum:
                            print('You rolled %d + %d = %d'%(y1,y2,sum2))
                            print('You win')
    
    
    dubo()
     
     
     
    You rolled 6 + 3 = 9
    point is 9
    You rolled 6 + 3 = 4
    You lose
    
     
    • 11

      去网上寻找如何用Python代码发送邮件

    In [ ]:
     
     
     
     
     
    # 简单邮件传输协议
    import smtplib
    import email
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    # 设置邮箱的域名
    HOST = 'smtp.qq.com'
    # 设置邮件标题
    SUBJECT = 'csdn博客代码'
    # 设置发件人邮箱
    FROM = '发件人邮箱@qq.com'
    # 设置收件人邮箱
    TO = '邮箱1@qq.com,邮箱2@qq.com'
    message = MIMEMultipart('related')
    
    
    #--------------------------------------发送文本-----------------
    # 发送邮件主体到对方的邮箱中
    message_html = MIMEText('<h2 >CSDN博客超级好</h2><img src="cid:big">','html','utf-8')
    message.attach(message_html)
    
    
    #-------------------------------------发送图片--------------------
    # rb  读取二进制文件
    # 要确定当前目录有1.jpg这个文件
    image_data = open('1.jpg','rb')
    # 设置读取获取的二进制数据
    message_image = MIMEImage(image_data.read())
    # 关闭刚才打开的文件
    image_data.close()
    message_image.add_header('Content-ID','big')
    # 添加图片文件到邮件信息当中去
    # message.attach(message_image)
    
    
    #-------------------------------------添加文件---------------------
    # 要确定当前目录有table.xls这个文件
    message_xlsx = MIMEText(open('table.xls','rb').read(),'base64','utf-8')
    # 设置文件在附件当中的名字
    message_xlsx['Content-Disposition'] = 'attachment;filename="test1111.xlsx"'
    message.attach(message_xlsx)
    
    
    # 设置邮件发件人
    message['From'] = FROM
    # 设置邮件收件人
    message['To'] = TO
    # 设置邮件标题
    message['Subject'] = SUBJECT
    
    
    # 获取简单邮件传输协议的证书
    email_client = smtplib.SMTP_SSL()
    # 设置发件人邮箱的域名和端口,端口为465
    email_client.connect(HOST,'465')
    # ---------------------------邮箱授权码------------------------------
    result = email_client.login(FROM,'邮箱授权码')
    print('登录结果',result)
    email_client.sendmail(from_addr=FROM,to_addrs=TO.split(','),msg=message.as_string())
    # 关闭邮件发送客户端
    email_client.close()

    函数

    • 函数可以用来定义可重复代码,组织和简化
    • 一般来说一个函数在实际开发中为一个小功能
    • 一个类为一个大功能
    • 同样函数的长度不要超过一屏
     

    Python中的所有函数实际上都是有返回值(return None),

    如果你没有设置return,那么Python将不显示None.

    如果你设置return,那么将返回出return这个值.

    In [29]:
     
     
     
     
     
    def HJN():
        print('Hello')
        return 1000
     
     
    In [30]:
     
     
     
     
     
    b=HJN()
    print(b)
     
     
     
    Hello
    1000
    
    In [3]:
     
     
     
     
     
    HJN
     
     
    Out[3]:
    <function __main__.HJN()>
    In [10]:
     
     
     
     
     
    def panduan(number):
        if number % 2 == 0:
            print('O')
        else:
            print('J')
     
     
    In [13]:
     
     
     
     
     
    panduan(number=1)
     
     
     
    J
    
    In [12]:
     
     
     
     
     
    panduan(2)
     
     
     
    O
    
     

    定义一个函数

    def function_name(list of parameters):

    do something

    • 以前使用的random 或者range 或者print.. 其实都是函数或者类
     

    函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.

    In [31]:
     
     
     
     
     
    import random
     
     
    In [ ]:
     
     
     
     
     
    def hahah():
        n = random.randint(0,5)
        while 1:
            N = eval(input('>>'))
            if n == N:
                print('smart')
                break
            elif n < N:
                print('太小了')
            elif n > N:
                print('太大了')
     
     
     

    调用一个函数

    • functionName()
    • "()" 就代表调用
    In [1]:
     
     
     
     
     
    def H():
        print('hahaha')
     
     
    In [2]:
     
     
     
     
     
    def B():
        H()
     
     
    In [3]:
     
     
     
     
     
    B()
     
     
     
    hahaha
    
    In [4]:
     
     
     
     
     
    def A(f):
        f()
     
     
    In [5]:
     
     
     
     
     
    A(B)
     
     
     
    hahaha
    
     

     

    带返回值和不带返回值的函数

    • return 返回的内容
    • return 返回多个值
    • 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
     

    • 当然也可以自定义返回None
     

    EP:

    In [8]:
     
     
     
     
     
    def main():
        print(min(min(5,6),(51,6)))
    def min(n1,n2):
        a = n1
        if n2 < a:
            a = n2
     
     
    In [9]:
     
     
     
     
     
    main()
     
     
     
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-9-263240bbee7e> in <module>
    ----> 1 main()
    
    <ipython-input-8-a7c84f32bfda> in main()
          1 def main():
    ----> 2     print(min(min(5,6),(51,6)))
          3 def min(n1,n2):
          4     a = n1
          5     if n2 < a:
    
    <ipython-input-8-a7c84f32bfda> in min(n1, n2)
          3 def min(n1,n2):
          4     a = n1
    ----> 5     if n2 < a:
          6         a = n2
    
    TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
    
    
     

    类型和关键字参数

    • 普通参数
    • 多个参数
    • 默认值参数
    • 不定长参数
     

    普通参数

     

    多个参数

     

    默认值参数

     

    强制命名

    In [60]:
     
     
     
     
     
    def U(str_):
        xiaoxie = 0
        for i in str_:
            ASCII = ord(i)
            if 97<=ASCII<=122:
                xiaoxie +=1
            elif xxxx:
                daxie += 1
            elif xxxx:
                shuzi += 1
        return xiaoxie,daxie,shuzi
     
     
    In [61]:
     
     
     
     
     
    U('HJi12')
     
     
     
    H
    J
    i
    1
    2
    
     

    不定长参数

    • *args
      • 不定长,来多少装多少,不装也是可以的
      • 返回的数据类型是元组
      • args 名字是可以修改的,只是我们约定俗成的是args
    • **kwargs
      • 返回的字典
      • 输入的一定要是表达式(键值对)
    • name,*args,name2,**kwargs 使用参数名
    In [ ]:
     
     
     
     
     
    def TT(a,b)
     
     
    In [51]:
     
     
     
     
     
    def TT(*args,**kwargs):
        print(kwargs)
        print(args)
    TT(1,2,3,4,6,a=100,b=1000)
     
     
     
    {'a': 100, 'b': 1000}
    (1, 2, 3, 4, 6)
    
    In [13]:
     
     
     
     
     
    {'key':'value'}
     
     
     
    ()
    
    In [14]:
     
     
     
     
     
    TT(1,2,4,5,7,8,9,)
     
     
     
    (1, 2, 4, 5, 7, 8, 9)
    
    In [38]:
     
     
     
     
     
    def B(name1,nam3):
        pass
     
     
    In [39]:
     
     
     
     
     
    B(name1=100,2)
     
     
     
      File "<ipython-input-39-bd6a38e58465>", line 1
        B(name1=100,2)
                   ^
    SyntaxError: positional argument follows keyword argument
    
    
    
    In [43]:
     
     
     
     
     
    def sum_(*args,A='sum'):
    
    
        res = 0
        count = 0
        for i in args:
            res +=i
            count += 1
        if A == "sum":
            return res
        elif A == "mean":
            mean = res / count
            return res,mean
        else:
            print(A,'还未开放')
    
    
    
    
     
     
    In [46]:
     
     
     
     
     
    sum_(-1,0,1,4,A='var')
     
     
     
    var 还未开放
    
    In [ ]:
     
     
     
     
     
    'aHbK134'.__iter__
     
     
    In [48]:
     
     
     
     
     
    b = 'asdkjfh'
    for i in b :
        print(i)
     
     
     
    a
    s
    d
    k
    j
    f
    h
    
    In [ ]:
     
     
     
     
     
    2,5
    2 + 22 + 222 + 2222 + 22222
     
     
     

    变量的作用域

    • 局部变量 local
    • 全局变量 global
    • globals 函数返回一个全局变量的字典,包括所有导入的变量
    • locals() 函数会以字典类型返回当前位置的全部局部变量。
    In [54]:
     
     
     
     
     
    a = 1000
    b = 10
    def Y():
        global a,b
        a += 100
        print(a)
    Y()
     
     
     
    1100
    
    In [55]:
     
     
     
     
     
    def YY(a1):
        a1 += 100
        print(a1)
    YY(a)
    print(a)
     
     
     
    1200
    1100
    
     

    注意:

    • global :在进行赋值操作的时候需要声明
    • 官方解释:This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
     

    Homework

    • 1
    In [13]:
     
     
     
     
     
    def getPentagonalNumber(n):
            c = 0
            for i in range(1,n+1):
                    he = int((i*(3*i - 1))/2)
                    print(he,end=' ')
                    c += 1
                    if c % 10 == 0:
                            print()
    getPentagonalNumber(100)  
    
    
    
    
     
     
     
    1 5 12 22 35 51 70 92 117 145 
    176 210 247 287 330 376 425 477 532 590 
    651 715 782 852 925 1001 1080 1162 1247 1335 
    1426 1520 1617 1717 1820 1926 2035 2147 2262 2380 
    2501 2625 2752 2882 3015 3151 3290 3432 3577 3725 
    3876 4030 4187 4347 4510 4676 4845 5017 5192 5370 
    5551 5735 5922 6112 6305 6501 6700 6902 7107 7315 
    7526 7740 7957 8177 8400 8626 8855 9087 9322 9560 
    9801 10045 10292 10542 10795 11051 11310 11572 11837 12105 
    12376 12650 12927 13207 13490 13776 14065 14357 14652 14950 
    
     
    • 2
    In [18]:
     
     
     
     
     
    def sumDigits(i):
    
    
        ge=i%10
        shi=i//10%10
        bai=i//100
        sum=ge + shi +bai
        print(sum)
    
    
    sumDigits(234)
    
    
     
     
     
    9
    
     
    • 3
    In [23]:
     
     
     
     
     
    def displaySortedNumbers(num1,num2,num3):
            shu = [num1,num2,num3]
            shen = sorted(shu)
            for i in range(len(shu)):
                  print(shen[i],end=" ")
    num1,num2,num3 = map(float,input('Enter three number: ').split(','))
    displaySortedNumbers(num1,num2,num3)
    
    
    
    
    
    
     
     
     
    Enter three number: 1,16,15
    1.0 15.0 16.0 
     
    • 4
    In [81]:
     
     
     
     
     
    def futureInvestmenValue(investmentAmount,monthlyInterestRate,years):
        for years in range(1,years):
            investmentAmount = float(investmentAmount+investmentAmount*monthlyInterestRate)
            print('%d            %.2f'%(years,investmentAmount))
    investmentAmount = float(input('The amount invested: '))
    monthlyInterestRate = float(input('Annual interest rate: '))*0.01
    print('years    Future Value')
    futureInvestmenValue(investmentAmount,monthlyInterestRate,31)
     
     
     
    The amount invested: 1000
    Annual interest rate: 9
    years    Future Value
    1            1090.00
    2            1188.10
    3            1295.03
    4            1411.58
    5            1538.62
    6            1677.10
    7            1828.04
    8            1992.56
    9            2171.89
    10            2367.36
    11            2580.43
    12            2812.66
    13            3065.80
    14            3341.73
    15            3642.48
    16            3970.31
    17            4327.63
    18            4717.12
    19            5141.66
    20            5604.41
    21            6108.81
    22            6658.60
    23            7257.87
    24            7911.08
    25            8623.08
    26            9399.16
    27            10245.08
    28            11167.14
    29            12172.18
    30            13267.68
    
     
    • 5
    In [80]:
     
     
     
     
     
    def printChars(ch1,ch2):
        count=0
        zimu=0
        for i in range(1,ch1):
            print(i,end=' ')
            count +=1
        for j in range(ord('A'),ch2+1):    
            print(chr(j),end=' ')
            zimu+=1
            sum=count+zimu
            if sum%10==0:
                print('\n')
    printChars(10,ord('Z'))
    
    
     
     
     
    1 2 3 4 5 6 7 8 9 A 
    
    B C D E F G H I J K 
    
    L M N O P Q R S T U 
    
    V W X Y Z 
     
    • 6
    In [82]:
     
     
     
     
     
    def numberOfDaysInAYear(year):
        for year in range(2010,year):
            if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
                print('%d年有366天'%year)
            else:
                print('%d年有365天'%year)
    
    
    numberOfDaysInAYear(2021)
     
     
     
    2010年有365天
    2011年有365天
    2012年有366天
    2013年有365天
    2014年有365天
    2015年有365天
    2016年有366天
    2017年有365天
    2018年有365天
    2019年有365天
    2020年有366天
    
     
    • 7
    In [83]:
     
     
     
     
     
    import math
    def distance(x1,y1,x2,y2):
        sum1 = (x1-x2) ** 2
        sum2 = (y1-y2) ** 2
        sum3 = math.sqrt(sum1 + sum2)
        print(sum3)
    x1 = int(input('x1= '))
    x2 = int(input('x2= '))
    y1 = int(input('y1= '))
    y2 = int(input('y2= '))
    distance(x1,y1,x2,y2)
     
     
     
    x1= 2
    x2= 3
    y1= 4
    y2= 5
    1.4142135623730951
    
     
    • 8
    In [84]:
     
     
     
     
     
    print('p      2^p - 1')
    def sushu():
        for i in range(2,32):
            for j in range(2,i):
                if i % j == 0:
                    break
            else: 
                for k in range(i+1):
                        if (2 ** k) - 1 == i:
                                print('%d        %d'%(k,i))
    sushu()
     
     
     
    p      2^p - 1
    2        3
    3        7
    5        31
    
     
    • 9
    In [1]:
     
     
     
     
     
    import time
     
     
    In [13]:
     
     
     
     
     
    import time
    localtime = time.asctime(time.localtime(time.time()))
    print("本地时间为 :", localtime)
     
     
     
    本地时间为 : Sat May 11 08:37:21 2019
    
    In [9]:
     
     
     
     
     
    2019 - 1970
     
     
    Out[9]:
    49
    In [ ]:
     
     
     
     
     
     
     
     
    • 10
    In [85]:
     
     
     
     
     
    import random
    x1 = random.randrange(1,7)
    x2 = random.randrange(1,7)
    sum = x1 + x2
    def dubo():
            if sum in [2,3,7,11,12]:
                    if sum in [2,3,12]:
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You lose')
                    else: 
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You win')
            if sum in [4,5,6,8,9,10]:
                    print('You rolled %d + %d = %d'%(x1,x2,sum))
                    print('point is %d'%sum)
                    y1 = random.randrange(1,7)
                    y2 = random.randrange(1,7)
                    sum2 = y1 + y2
                    if sum2 != sum:
                            print('You rolled %d + %d = %d'%(x1,x2,sum2))
                            print('You lose')
                    elif sum2 == sum:
                            print('You rolled %d + %d = %d'%(y1,y2,sum2))
                            print('You win')
    
    
    dubo()
     
     
     
    You rolled 6 + 3 = 9
    point is 9
    You rolled 6 + 3 = 4
    You lose
    
     
    • 11

      去网上寻找如何用Python代码发送邮件

    In [ ]:
     
     
     
     
     
    # 简单邮件传输协议
    import smtplib
    import email
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    # 设置邮箱的域名
    HOST = 'smtp.qq.com'
    # 设置邮件标题
    SUBJECT = 'csdn博客代码'
    # 设置发件人邮箱
    FROM = '发件人邮箱@qq.com'
    # 设置收件人邮箱
    TO = '邮箱1@qq.com,邮箱2@qq.com'
    message = MIMEMultipart('related')
    
    
    #--------------------------------------发送文本-----------------
    # 发送邮件主体到对方的邮箱中
    message_html = MIMEText('<h2 >CSDN博客超级好</h2><img src="cid:big">','html','utf-8')
    message.attach(message_html)
    
    
    #-------------------------------------发送图片--------------------
    # rb  读取二进制文件
    # 要确定当前目录有1.jpg这个文件
    image_data = open('1.jpg','rb')
    # 设置读取获取的二进制数据
    message_image = MIMEImage(image_data.read())
    # 关闭刚才打开的文件
    image_data.close()
    message_image.add_header('Content-ID','big')
    # 添加图片文件到邮件信息当中去
    # message.attach(message_image)
    
    
    #-------------------------------------添加文件---------------------
    # 要确定当前目录有table.xls这个文件
    message_xlsx = MIMEText(open('table.xls','rb').read(),'base64','utf-8')
    # 设置文件在附件当中的名字
    message_xlsx['Content-Disposition'] = 'attachment;filename="test1111.xlsx"'
    message.attach(message_xlsx)
    
    
    # 设置邮件发件人
    message['From'] = FROM
    # 设置邮件收件人
    message['To'] = TO
    # 设置邮件标题
    message['Subject'] = SUBJECT
    
    
    # 获取简单邮件传输协议的证书
    email_client = smtplib.SMTP_SSL()
    # 设置发件人邮箱的域名和端口,端口为465
    email_client.connect(HOST,'465')
    # ---------------------------邮箱授权码------------------------------
    result = email_client.login(FROM,'邮箱授权码')
    print('登录结果',result)
    email_client.sendmail(from_addr=FROM,to_addrs=TO.split(','),msg=message.as_string())
    # 关闭邮件发送客户端
    email_client.close()

    函数

    • 函数可以用来定义可重复代码,组织和简化
    • 一般来说一个函数在实际开发中为一个小功能
    • 一个类为一个大功能
    • 同样函数的长度不要超过一屏
     

    Python中的所有函数实际上都是有返回值(return None),

    如果你没有设置return,那么Python将不显示None.

    如果你设置return,那么将返回出return这个值.

    In [29]:
     
     
     
     
     
    def HJN():
        print('Hello')
        return 1000
     
     
    In [30]:
     
     
     
     
     
    b=HJN()
    print(b)
     
     
     
    Hello
    1000
    
    In [3]:
     
     
     
     
     
    HJN
     
     
    Out[3]:
    <function __main__.HJN()>
    In [10]:
     
     
     
     
     
    def panduan(number):
        if number % 2 == 0:
            print('O')
        else:
            print('J')
     
     
    In [13]:
     
     
     
     
     
    panduan(number=1)
     
     
     
    J
    
    In [12]:
     
     
     
     
     
    panduan(2)
     
     
     
    O
    
     

    定义一个函数

    def function_name(list of parameters):

    do something

    • 以前使用的random 或者range 或者print.. 其实都是函数或者类
     

    函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.

    In [31]:
     
     
     
     
     
    import random
     
     
    In [ ]:
     
     
     
     
     
    def hahah():
        n = random.randint(0,5)
        while 1:
            N = eval(input('>>'))
            if n == N:
                print('smart')
                break
            elif n < N:
                print('太小了')
            elif n > N:
                print('太大了')
     
     
     

    调用一个函数

    • functionName()
    • "()" 就代表调用
    In [1]:
     
     
     
     
     
    def H():
        print('hahaha')
     
     
    In [2]:
     
     
     
     
     
    def B():
        H()
     
     
    In [3]:
     
     
     
     
     
    B()
     
     
     
    hahaha
    
    In [4]:
     
     
     
     
     
    def A(f):
        f()
     
     
    In [5]:
     
     
     
     
     
    A(B)
     
     
     
    hahaha
    
     

     

    带返回值和不带返回值的函数

    • return 返回的内容
    • return 返回多个值
    • 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
     

    • 当然也可以自定义返回None
     

    EP:

    In [8]:
     
     
     
     
     
    def main():
        print(min(min(5,6),(51,6)))
    def min(n1,n2):
        a = n1
        if n2 < a:
            a = n2
     
     
    In [9]:
     
     
     
     
     
    main()
     
     
     
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-9-263240bbee7e> in <module>
    ----> 1 main()
    
    <ipython-input-8-a7c84f32bfda> in main()
          1 def main():
    ----> 2     print(min(min(5,6),(51,6)))
          3 def min(n1,n2):
          4     a = n1
          5     if n2 < a:
    
    <ipython-input-8-a7c84f32bfda> in min(n1, n2)
          3 def min(n1,n2):
          4     a = n1
    ----> 5     if n2 < a:
          6         a = n2
    
    TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
    
    
     

    类型和关键字参数

    • 普通参数
    • 多个参数
    • 默认值参数
    • 不定长参数
     

    普通参数

     

    多个参数

     

    默认值参数

     

    强制命名

    In [60]:
     
     
     
     
     
    def U(str_):
        xiaoxie = 0
        for i in str_:
            ASCII = ord(i)
            if 97<=ASCII<=122:
                xiaoxie +=1
            elif xxxx:
                daxie += 1
            elif xxxx:
                shuzi += 1
        return xiaoxie,daxie,shuzi
     
     
    In [61]:
     
     
     
     
     
    U('HJi12')
     
     
     
    H
    J
    i
    1
    2
    
     

    不定长参数

    • *args
      • 不定长,来多少装多少,不装也是可以的
      • 返回的数据类型是元组
      • args 名字是可以修改的,只是我们约定俗成的是args
    • **kwargs
      • 返回的字典
      • 输入的一定要是表达式(键值对)
    • name,*args,name2,**kwargs 使用参数名
    In [ ]:
     
     
     
     
     
    def TT(a,b)
     
     
    In [51]:
     
     
     
     
     
    def TT(*args,**kwargs):
        print(kwargs)
        print(args)
    TT(1,2,3,4,6,a=100,b=1000)
     
     
     
    {'a': 100, 'b': 1000}
    (1, 2, 3, 4, 6)
    
    In [13]:
     
     
     
     
     
    {'key':'value'}
     
     
     
    ()
    
    In [14]:
     
     
     
     
     
    TT(1,2,4,5,7,8,9,)
     
     
     
    (1, 2, 4, 5, 7, 8, 9)
    
    In [38]:
     
     
     
     
     
    def B(name1,nam3):
        pass
     
     
    In [39]:
     
     
     
     
     
    B(name1=100,2)
     
     
     
      File "<ipython-input-39-bd6a38e58465>", line 1
        B(name1=100,2)
                   ^
    SyntaxError: positional argument follows keyword argument
    
    
    
    In [43]:
     
     
     
     
     
    def sum_(*args,A='sum'):
    
    
        res = 0
        count = 0
        for i in args:
            res +=i
            count += 1
        if A == "sum":
            return res
        elif A == "mean":
            mean = res / count
            return res,mean
        else:
            print(A,'还未开放')
    
    
    
    
     
     
    In [46]:
     
     
     
     
     
    sum_(-1,0,1,4,A='var')
     
     
     
    var 还未开放
    
    In [ ]:
     
     
     
     
     
    'aHbK134'.__iter__
     
     
    In [48]:
     
     
     
     
     
    b = 'asdkjfh'
    for i in b :
        print(i)
     
     
     
    a
    s
    d
    k
    j
    f
    h
    
    In [ ]:
     
     
     
     
     
    2,5
    2 + 22 + 222 + 2222 + 22222
     
     
     

    变量的作用域

    • 局部变量 local
    • 全局变量 global
    • globals 函数返回一个全局变量的字典,包括所有导入的变量
    • locals() 函数会以字典类型返回当前位置的全部局部变量。
    In [54]:
     
     
     
     
     
    a = 1000
    b = 10
    def Y():
        global a,b
        a += 100
        print(a)
    Y()
     
     
     
    1100
    
    In [55]:
     
     
     
     
     
    def YY(a1):
        a1 += 100
        print(a1)
    YY(a)
    print(a)
     
     
     
    1200
    1100
    
     

    注意:

    • global :在进行赋值操作的时候需要声明
    • 官方解释:This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
     

    Homework

    • 1
    In [13]:
     
     
     
     
     
    def getPentagonalNumber(n):
            c = 0
            for i in range(1,n+1):
                    he = int((i*(3*i - 1))/2)
                    print(he,end=' ')
                    c += 1
                    if c % 10 == 0:
                            print()
    getPentagonalNumber(100)  
    
    
    
    
     
     
     
    1 5 12 22 35 51 70 92 117 145 
    176 210 247 287 330 376 425 477 532 590 
    651 715 782 852 925 1001 1080 1162 1247 1335 
    1426 1520 1617 1717 1820 1926 2035 2147 2262 2380 
    2501 2625 2752 2882 3015 3151 3290 3432 3577 3725 
    3876 4030 4187 4347 4510 4676 4845 5017 5192 5370 
    5551 5735 5922 6112 6305 6501 6700 6902 7107 7315 
    7526 7740 7957 8177 8400 8626 8855 9087 9322 9560 
    9801 10045 10292 10542 10795 11051 11310 11572 11837 12105 
    12376 12650 12927 13207 13490 13776 14065 14357 14652 14950 
    
     
    • 2
    In [18]:
     
     
     
     
     
    def sumDigits(i):
    
    
        ge=i%10
        shi=i//10%10
        bai=i//100
        sum=ge + shi +bai
        print(sum)
    
    
    sumDigits(234)
    
    
     
     
     
    9
    
     
    • 3
    In [23]:
     
     
     
     
     
    def displaySortedNumbers(num1,num2,num3):
            shu = [num1,num2,num3]
            shen = sorted(shu)
            for i in range(len(shu)):
                  print(shen[i],end=" ")
    num1,num2,num3 = map(float,input('Enter three number: ').split(','))
    displaySortedNumbers(num1,num2,num3)
    
    
    
    
    
    
     
     
     
    Enter three number: 1,16,15
    1.0 15.0 16.0 
     
    • 4
    In [81]:
     
     
     
     
     
    def futureInvestmenValue(investmentAmount,monthlyInterestRate,years):
        for years in range(1,years):
            investmentAmount = float(investmentAmount+investmentAmount*monthlyInterestRate)
            print('%d            %.2f'%(years,investmentAmount))
    investmentAmount = float(input('The amount invested: '))
    monthlyInterestRate = float(input('Annual interest rate: '))*0.01
    print('years    Future Value')
    futureInvestmenValue(investmentAmount,monthlyInterestRate,31)
     
     
     
    The amount invested: 1000
    Annual interest rate: 9
    years    Future Value
    1            1090.00
    2            1188.10
    3            1295.03
    4            1411.58
    5            1538.62
    6            1677.10
    7            1828.04
    8            1992.56
    9            2171.89
    10            2367.36
    11            2580.43
    12            2812.66
    13            3065.80
    14            3341.73
    15            3642.48
    16            3970.31
    17            4327.63
    18            4717.12
    19            5141.66
    20            5604.41
    21            6108.81
    22            6658.60
    23            7257.87
    24            7911.08
    25            8623.08
    26            9399.16
    27            10245.08
    28            11167.14
    29            12172.18
    30            13267.68
    
     
    • 5
    In [80]:
     
     
     
     
     
    def printChars(ch1,ch2):
        count=0
        zimu=0
        for i in range(1,ch1):
            print(i,end=' ')
            count +=1
        for j in range(ord('A'),ch2+1):    
            print(chr(j),end=' ')
            zimu+=1
            sum=count+zimu
            if sum%10==0:
                print('\n')
    printChars(10,ord('Z'))
    
    
     
     
     
    1 2 3 4 5 6 7 8 9 A 
    
    B C D E F G H I J K 
    
    L M N O P Q R S T U 
    
    V W X Y Z 
     
    • 6
    In [82]:
     
     
     
     
     
    def numberOfDaysInAYear(year):
        for year in range(2010,year):
            if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
                print('%d年有366天'%year)
            else:
                print('%d年有365天'%year)
    
    
    numberOfDaysInAYear(2021)
     
     
     
    2010年有365天
    2011年有365天
    2012年有366天
    2013年有365天
    2014年有365天
    2015年有365天
    2016年有366天
    2017年有365天
    2018年有365天
    2019年有365天
    2020年有366天
    
     
    • 7
    In [83]:
     
     
     
     
     
    import math
    def distance(x1,y1,x2,y2):
        sum1 = (x1-x2) ** 2
        sum2 = (y1-y2) ** 2
        sum3 = math.sqrt(sum1 + sum2)
        print(sum3)
    x1 = int(input('x1= '))
    x2 = int(input('x2= '))
    y1 = int(input('y1= '))
    y2 = int(input('y2= '))
    distance(x1,y1,x2,y2)
     
     
     
    x1= 2
    x2= 3
    y1= 4
    y2= 5
    1.4142135623730951
    
     
    • 8
    In [84]:
     
     
     
     
     
    print('p      2^p - 1')
    def sushu():
        for i in range(2,32):
            for j in range(2,i):
                if i % j == 0:
                    break
            else: 
                for k in range(i+1):
                        if (2 ** k) - 1 == i:
                                print('%d        %d'%(k,i))
    sushu()
     
     
     
    p      2^p - 1
    2        3
    3        7
    5        31
    
     
    • 9
    In [1]:
     
     
     
     
     
    import time
     
     
    In [13]:
     
     
     
     
     
    import time
    localtime = time.asctime(time.localtime(time.time()))
    print("本地时间为 :", localtime)
     
     
     
    本地时间为 : Sat May 11 08:37:21 2019
    
    In [9]:
     
     
     
     
     
    2019 - 1970
     
     
    Out[9]:
    49
    In [ ]:
     
     
     
     
     
     
     
     
    • 10
    In [85]:
     
     
     
     
     
    import random
    x1 = random.randrange(1,7)
    x2 = random.randrange(1,7)
    sum = x1 + x2
    def dubo():
            if sum in [2,3,7,11,12]:
                    if sum in [2,3,12]:
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You lose')
                    else: 
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You win')
            if sum in [4,5,6,8,9,10]:
                    print('You rolled %d + %d = %d'%(x1,x2,sum))
                    print('point is %d'%sum)
                    y1 = random.randrange(1,7)
                    y2 = random.randrange(1,7)
                    sum2 = y1 + y2
                    if sum2 != sum:
                            print('You rolled %d + %d = %d'%(x1,x2,sum2))
                            print('You lose')
                    elif sum2 == sum:
                            print('You rolled %d + %d = %d'%(y1,y2,sum2))
                            print('You win')
    
    
    dubo()
     
     
     
    You rolled 6 + 3 = 9
    point is 9
    You rolled 6 + 3 = 4
    You lose
    
     
    • 11

      去网上寻找如何用Python代码发送邮件

    In [ ]:
     
     
     
     
     
    # 简单邮件传输协议
    import smtplib
    import email
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    # 设置邮箱的域名
    HOST = 'smtp.qq.com'
    # 设置邮件标题
    SUBJECT = 'csdn博客代码'
    # 设置发件人邮箱
    FROM = '发件人邮箱@qq.com'
    # 设置收件人邮箱
    TO = '邮箱1@qq.com,邮箱2@qq.com'
    message = MIMEMultipart('related')
    
    
    #--------------------------------------发送文本-----------------
    # 发送邮件主体到对方的邮箱中
    message_html = MIMEText('<h2 >CSDN博客超级好</h2><img src="cid:big">','html','utf-8')
    message.attach(message_html)
    
    
    #-------------------------------------发送图片--------------------
    # rb  读取二进制文件
    # 要确定当前目录有1.jpg这个文件
    image_data = open('1.jpg','rb')
    # 设置读取获取的二进制数据
    message_image = MIMEImage(image_data.read())
    # 关闭刚才打开的文件
    image_data.close()
    message_image.add_header('Content-ID','big')
    # 添加图片文件到邮件信息当中去
    # message.attach(message_image)
    
    
    #-------------------------------------添加文件---------------------
    # 要确定当前目录有table.xls这个文件
    message_xlsx = MIMEText(open('table.xls','rb').read(),'base64','utf-8')
    # 设置文件在附件当中的名字
    message_xlsx['Content-Disposition'] = 'attachment;filename="test1111.xlsx"'
    message.attach(message_xlsx)
    
    
    # 设置邮件发件人
    message['From'] = FROM
    # 设置邮件收件人
    message['To'] = TO
    # 设置邮件标题
    message['Subject'] = SUBJECT
    
    
    # 获取简单邮件传输协议的证书
    email_client = smtplib.SMTP_SSL()
    # 设置发件人邮箱的域名和端口,端口为465
    email_client.connect(HOST,'465')
    # ---------------------------邮箱授权码------------------------------
    result = email_client.login(FROM,'邮箱授权码')
    print('登录结果',result)
    email_client.sendmail(from_addr=FROM,to_addrs=TO.split(','),msg=message.as_string())
    # 关闭邮件发送客户端
    email_client.close()

    函数

    • 函数可以用来定义可重复代码,组织和简化
    • 一般来说一个函数在实际开发中为一个小功能
    • 一个类为一个大功能
    • 同样函数的长度不要超过一屏
     

    Python中的所有函数实际上都是有返回值(return None),

    如果你没有设置return,那么Python将不显示None.

    如果你设置return,那么将返回出return这个值.

    In [29]:
     
     
     
     
     
    def HJN():
        print('Hello')
        return 1000
     
     
    In [30]:
     
     
     
     
     
    b=HJN()
    print(b)
     
     
     
    Hello
    1000
    
    In [3]:
     
     
     
     
     
    HJN
     
     
    Out[3]:
    <function __main__.HJN()>
    In [10]:
     
     
     
     
     
    def panduan(number):
        if number % 2 == 0:
            print('O')
        else:
            print('J')
     
     
    In [13]:
     
     
     
     
     
    panduan(number=1)
     
     
     
    J
    
    In [12]:
     
     
     
     
     
    panduan(2)
     
     
     
    O
    
     

    定义一个函数

    def function_name(list of parameters):

    do something

    • 以前使用的random 或者range 或者print.. 其实都是函数或者类
     

    函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.

    In [31]:
     
     
     
     
     
    import random
     
     
    In [ ]:
     
     
     
     
     
    def hahah():
        n = random.randint(0,5)
        while 1:
            N = eval(input('>>'))
            if n == N:
                print('smart')
                break
            elif n < N:
                print('太小了')
            elif n > N:
                print('太大了')
     
     
     

    调用一个函数

    • functionName()
    • "()" 就代表调用
    In [1]:
     
     
     
     
     
    def H():
        print('hahaha')
     
     
    In [2]:
     
     
     
     
     
    def B():
        H()
     
     
    In [3]:
     
     
     
     
     
    B()
     
     
     
    hahaha
    
    In [4]:
     
     
     
     
     
    def A(f):
        f()
     
     
    In [5]:
     
     
     
     
     
    A(B)
     
     
     
    hahaha
    
     

     

    带返回值和不带返回值的函数

    • return 返回的内容
    • return 返回多个值
    • 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
     

    • 当然也可以自定义返回None
     

    EP:

    In [8]:
     
     
     
     
     
    def main():
        print(min(min(5,6),(51,6)))
    def min(n1,n2):
        a = n1
        if n2 < a:
            a = n2
     
     
    In [9]:
     
     
     
     
     
    main()
     
     
     
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-9-263240bbee7e> in <module>
    ----> 1 main()
    
    <ipython-input-8-a7c84f32bfda> in main()
          1 def main():
    ----> 2     print(min(min(5,6),(51,6)))
          3 def min(n1,n2):
          4     a = n1
          5     if n2 < a:
    
    <ipython-input-8-a7c84f32bfda> in min(n1, n2)
          3 def min(n1,n2):
          4     a = n1
    ----> 5     if n2 < a:
          6         a = n2
    
    TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
    
    
     

    类型和关键字参数

    • 普通参数
    • 多个参数
    • 默认值参数
    • 不定长参数
     

    普通参数

     

    多个参数

     

    默认值参数

     

    强制命名

    In [60]:
     
     
     
     
     
    def U(str_):
        xiaoxie = 0
        for i in str_:
            ASCII = ord(i)
            if 97<=ASCII<=122:
                xiaoxie +=1
            elif xxxx:
                daxie += 1
            elif xxxx:
                shuzi += 1
        return xiaoxie,daxie,shuzi
     
     
    In [61]:
     
     
     
     
     
    U('HJi12')
     
     
     
    H
    J
    i
    1
    2
    
     

    不定长参数

    • *args
      • 不定长,来多少装多少,不装也是可以的
      • 返回的数据类型是元组
      • args 名字是可以修改的,只是我们约定俗成的是args
    • **kwargs
      • 返回的字典
      • 输入的一定要是表达式(键值对)
    • name,*args,name2,**kwargs 使用参数名
    In [ ]:
     
     
     
     
     
    def TT(a,b)
     
     
    In [51]:
     
     
     
     
     
    def TT(*args,**kwargs):
        print(kwargs)
        print(args)
    TT(1,2,3,4,6,a=100,b=1000)
     
     
     
    {'a': 100, 'b': 1000}
    (1, 2, 3, 4, 6)
    
    In [13]:
     
     
     
     
     
    {'key':'value'}
     
     
     
    ()
    
    In [14]:
     
     
     
     
     
    TT(1,2,4,5,7,8,9,)
     
     
     
    (1, 2, 4, 5, 7, 8, 9)
    
    In [38]:
     
     
     
     
     
    def B(name1,nam3):
        pass
     
     
    In [39]:
     
     
     
     
     
    B(name1=100,2)
     
     
     
      File "<ipython-input-39-bd6a38e58465>", line 1
        B(name1=100,2)
                   ^
    SyntaxError: positional argument follows keyword argument
    
    
    
    In [43]:
     
     
     
     
     
    def sum_(*args,A='sum'):
    
    
        res = 0
        count = 0
        for i in args:
            res +=i
            count += 1
        if A == "sum":
            return res
        elif A == "mean":
            mean = res / count
            return res,mean
        else:
            print(A,'还未开放')
    
    
    
    
     
     
    In [46]:
     
     
     
     
     
    sum_(-1,0,1,4,A='var')
     
     
     
    var 还未开放
    
    In [ ]:
     
     
     
     
     
    'aHbK134'.__iter__
     
     
    In [48]:
     
     
     
     
     
    b = 'asdkjfh'
    for i in b :
        print(i)
     
     
     
    a
    s
    d
    k
    j
    f
    h
    
    In [ ]:
     
     
     
     
     
    2,5
    2 + 22 + 222 + 2222 + 22222
     
     
     

    变量的作用域

    • 局部变量 local
    • 全局变量 global
    • globals 函数返回一个全局变量的字典,包括所有导入的变量
    • locals() 函数会以字典类型返回当前位置的全部局部变量。
    In [54]:
     
     
     
     
     
    a = 1000
    b = 10
    def Y():
        global a,b
        a += 100
        print(a)
    Y()
     
     
     
    1100
    
    In [55]:
     
     
     
     
     
    def YY(a1):
        a1 += 100
        print(a1)
    YY(a)
    print(a)
     
     
     
    1200
    1100
    
     

    注意:

    • global :在进行赋值操作的时候需要声明
    • 官方解释:This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
     

    Homework

    • 1
    In [13]:
     
     
     
     
     
    def getPentagonalNumber(n):
            c = 0
            for i in range(1,n+1):
                    he = int((i*(3*i - 1))/2)
                    print(he,end=' ')
                    c += 1
                    if c % 10 == 0:
                            print()
    getPentagonalNumber(100)  
    
    
    
    
     
     
     
    1 5 12 22 35 51 70 92 117 145 
    176 210 247 287 330 376 425 477 532 590 
    651 715 782 852 925 1001 1080 1162 1247 1335 
    1426 1520 1617 1717 1820 1926 2035 2147 2262 2380 
    2501 2625 2752 2882 3015 3151 3290 3432 3577 3725 
    3876 4030 4187 4347 4510 4676 4845 5017 5192 5370 
    5551 5735 5922 6112 6305 6501 6700 6902 7107 7315 
    7526 7740 7957 8177 8400 8626 8855 9087 9322 9560 
    9801 10045 10292 10542 10795 11051 11310 11572 11837 12105 
    12376 12650 12927 13207 13490 13776 14065 14357 14652 14950 
    
     
    • 2
    In [18]:
     
     
     
     
     
    def sumDigits(i):
    
    
        ge=i%10
        shi=i//10%10
        bai=i//100
        sum=ge + shi +bai
        print(sum)
    
    
    sumDigits(234)
    
    
     
     
     
    9
    
     
    • 3
    In [23]:
     
     
     
     
     
    def displaySortedNumbers(num1,num2,num3):
            shu = [num1,num2,num3]
            shen = sorted(shu)
            for i in range(len(shu)):
                  print(shen[i],end=" ")
    num1,num2,num3 = map(float,input('Enter three number: ').split(','))
    displaySortedNumbers(num1,num2,num3)
    
    
    
    
    
    
     
     
     
    Enter three number: 1,16,15
    1.0 15.0 16.0 
     
    • 4
    In [81]:
     
     
     
     
     
    def futureInvestmenValue(investmentAmount,monthlyInterestRate,years):
        for years in range(1,years):
            investmentAmount = float(investmentAmount+investmentAmount*monthlyInterestRate)
            print('%d            %.2f'%(years,investmentAmount))
    investmentAmount = float(input('The amount invested: '))
    monthlyInterestRate = float(input('Annual interest rate: '))*0.01
    print('years    Future Value')
    futureInvestmenValue(investmentAmount,monthlyInterestRate,31)
     
     
     
    The amount invested: 1000
    Annual interest rate: 9
    years    Future Value
    1            1090.00
    2            1188.10
    3            1295.03
    4            1411.58
    5            1538.62
    6            1677.10
    7            1828.04
    8            1992.56
    9            2171.89
    10            2367.36
    11            2580.43
    12            2812.66
    13            3065.80
    14            3341.73
    15            3642.48
    16            3970.31
    17            4327.63
    18            4717.12
    19            5141.66
    20            5604.41
    21            6108.81
    22            6658.60
    23            7257.87
    24            7911.08
    25            8623.08
    26            9399.16
    27            10245.08
    28            11167.14
    29            12172.18
    30            13267.68
    
     
    • 5
    In [80]:
     
     
     
     
     
    def printChars(ch1,ch2):
        count=0
        zimu=0
        for i in range(1,ch1):
            print(i,end=' ')
            count +=1
        for j in range(ord('A'),ch2+1):    
            print(chr(j),end=' ')
            zimu+=1
            sum=count+zimu
            if sum%10==0:
                print('\n')
    printChars(10,ord('Z'))
    
    
     
     
     
    1 2 3 4 5 6 7 8 9 A 
    
    B C D E F G H I J K 
    
    L M N O P Q R S T U 
    
    V W X Y Z 
     
    • 6
    In [82]:
     
     
     
     
     
    def numberOfDaysInAYear(year):
        for year in range(2010,year):
            if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
                print('%d年有366天'%year)
            else:
                print('%d年有365天'%year)
    
    
    numberOfDaysInAYear(2021)
     
     
     
    2010年有365天
    2011年有365天
    2012年有366天
    2013年有365天
    2014年有365天
    2015年有365天
    2016年有366天
    2017年有365天
    2018年有365天
    2019年有365天
    2020年有366天
    
     
    • 7
    In [83]:
     
     
     
     
     
    import math
    def distance(x1,y1,x2,y2):
        sum1 = (x1-x2) ** 2
        sum2 = (y1-y2) ** 2
        sum3 = math.sqrt(sum1 + sum2)
        print(sum3)
    x1 = int(input('x1= '))
    x2 = int(input('x2= '))
    y1 = int(input('y1= '))
    y2 = int(input('y2= '))
    distance(x1,y1,x2,y2)
     
     
     
    x1= 2
    x2= 3
    y1= 4
    y2= 5
    1.4142135623730951
    
     
    • 8
    In [84]:
     
     
     
     
     
    print('p      2^p - 1')
    def sushu():
        for i in range(2,32):
            for j in range(2,i):
                if i % j == 0:
                    break
            else: 
                for k in range(i+1):
                        if (2 ** k) - 1 == i:
                                print('%d        %d'%(k,i))
    sushu()
     
     
     
    p      2^p - 1
    2        3
    3        7
    5        31
    
     
    • 9
    In [1]:
     
     
     
     
     
    import time
     
     
    In [13]:
     
     
     
     
     
    import time
    localtime = time.asctime(time.localtime(time.time()))
    print("本地时间为 :", localtime)
     
     
     
    本地时间为 : Sat May 11 08:37:21 2019
    
    In [9]:
     
     
     
     
     
    2019 - 1970
     
     
    Out[9]:
    49
    In [ ]:
     
     
     
     
     
     
     
     
    • 10
    In [85]:
     
     
     
     
     
    import random
    x1 = random.randrange(1,7)
    x2 = random.randrange(1,7)
    sum = x1 + x2
    def dubo():
            if sum in [2,3,7,11,12]:
                    if sum in [2,3,12]:
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You lose')
                    else: 
                            print('You rolled %d + %d = %d'%(x1,x2,sum))
                            print('You win')
            if sum in [4,5,6,8,9,10]:
                    print('You rolled %d + %d = %d'%(x1,x2,sum))
                    print('point is %d'%sum)
                    y1 = random.randrange(1,7)
                    y2 = random.randrange(1,7)
                    sum2 = y1 + y2
                    if sum2 != sum:
                            print('You rolled %d + %d = %d'%(x1,x2,sum2))
                            print('You lose')
                    elif sum2 == sum:
                            print('You rolled %d + %d = %d'%(y1,y2,sum2))
                            print('You win')
    
    
    dubo()
     
     
     
    You rolled 6 + 3 = 9
    point is 9
    You rolled 6 + 3 = 4
    You lose
    
     
    • 11

      去网上寻找如何用Python代码发送邮件

    In [ ]:
     
     
     
     
     
    # 简单邮件传输协议
    import smtplib
    import email
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    # 设置邮箱的域名
    HOST = 'smtp.qq.com'
    # 设置邮件标题
    SUBJECT = 'csdn博客代码'
    # 设置发件人邮箱
    FROM = '发件人邮箱@qq.com'
    # 设置收件人邮箱
    TO = '邮箱1@qq.com,邮箱2@qq.com'
    message = MIMEMultipart('related')
    
    
    #--------------------------------------发送文本-----------------
    # 发送邮件主体到对方的邮箱中
    message_html = MIMEText('<h2 >CSDN博客超级好</h2><img src="cid:big">','html','utf-8')
    message.attach(message_html)
    
    
    #-------------------------------------发送图片--------------------
    # rb  读取二进制文件
    # 要确定当前目录有1.jpg这个文件
    image_data = open('1.jpg','rb')
    # 设置读取获取的二进制数据
    message_image = MIMEImage(image_data.read())
    # 关闭刚才打开的文件
    image_data.close()
    message_image.add_header('Content-ID','big')
    # 添加图片文件到邮件信息当中去
    # message.attach(message_image)
    
    
    #-------------------------------------添加文件---------------------
    # 要确定当前目录有table.xls这个文件
    message_xlsx = MIMEText(open('table.xls','rb').read(),'base64','utf-8')
    # 设置文件在附件当中的名字
    message_xlsx['Content-Disposition'] = 'attachment;filename="test1111.xlsx"'
    message.attach(message_xlsx)
    
    
    # 设置邮件发件人
    message['From'] = FROM
    # 设置邮件收件人
    message['To'] = TO
    # 设置邮件标题
    message['Subject'] = SUBJECT
    
    
    # 获取简单邮件传输协议的证书
    email_client = smtplib.SMTP_SSL()
    # 设置发件人邮箱的域名和端口,端口为465
    email_client.connect(HOST,'465')
    # ---------------------------邮箱授权码------------------------------
    result = email_client.login(FROM,'邮箱授权码')
    print('登录结果',result)
    email_client.sendmail(from_addr=FROM,to_addrs=TO.split(','),msg=message.as_string())
    # 关闭邮件发送客户端
    email_client.close()
  • 相关阅读:
    linux系列之-—03 压缩和解压缩命令
    Atlassian Confluence安装
    常见ODBC及OLEDB连接串的写法
    windows 怎么验证域名是否开启了 https
    Jenkins基础篇 系列之-—05 集成JIRA
    SVN系列之—-SVN版本回滚的办法
    JMeter 系列之—-02 创建数据库测试计划
    golang web框架 beego 学习 (一) 环境搭建
    补充 3:Golang 一些特性
    补充 1: panic 、recover、 defer
  • 原文地址:https://www.cnblogs.com/wangzhehui/p/11345568.html
Copyright © 2011-2022 走看看