函数

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

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

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

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

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

定义一个函数

def function_name(list of parameters):

  1. do something
  1.  

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

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

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

调用一个函数

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

 

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

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

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

EP:

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

类型和关键字参数

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

普通参数

 

多个参数

 

默认值参数

 

强制命名

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

不定长参数

  • *args

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

变量的作用域

  • 局部变量 local
  • 全局变量 global
  • globals 函数返回一个全局变量的字典,包括所有导入的变量
  • locals() 函数会以字典类型返回当前位置的全部局部变量。
In [54]:
 
 
 
 
 
  1. a = 1000
  1. b = 10
  1. def Y():
  1. global a,b
  1. a += 100
  1. print(a)
  1. Y()
 
 
 
  1. 1100
In [55]:
 
 
 
 
 
  1. def YY(a1):
  1. a1 += 100
  1. print(a1)
  1. YY(a)
  1. print(a)
 
 
 
  1. 1200
  2. 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 [ ]:
 
 
 
 
 
  1. import math
  1. def getPentagonalNumber():
  1. count = 0
  1. for i in range(1, 101):
  1. a = i * ( 3*i - 1) / 2
  1. print(int(a),end = ' ')
  1. count += 1
  1. if count % 10 == 0:
  1. print('\n')
  1. getPentagonalNumber()
 
 
 
  • 2
In [1]:
 
 
 
 
 
  1. def sumDigits(n):
  1. a = n % 10
  1. b = n // 100
  1. c = (n // 10) - ((n // 100)*10)
  1. d = a + b + c
  1. print(d)
  1. sumDigits(234)
 
 
 
  1. 9
 
  • 3
In [2]:
 
 
 
 
 
  1. def displaySortedNumbers(num1,num2,num3):
  1. if num1 > num2 > num3:
  1. print(num1,num2,num3)
  1. elif num1 > num3 > num2:
  1. print(num1,num3,num2)
  1. elif num2 > num1 > num3:
  1. print(num2,num1,num3)
  1. elif num2 > num3 > num1:
  1. print(num2,num3,num1)
  1. elif num3 > num1 > num2:
  1. print(num3,num1,num2)
  1. elif num3 > num2 > num1:
  1. print(num3,num2,num1)
  1. displaySortedNumbers(3,8,1)
 
 
 
  1. 8 3 1
 
  • 4
In [2]:
 
 
 
 
 
  1. def futureInvestmentValue(principal,rate,years):
  1. for i in range(years):
  1. principal = principal * (1+rate)
  1. print("{}年内总额{}: ".format(i+1,principal))
  1. principal = eval(input("输入存款金额: "))
  1. rate = eval(input("输入利率: "))
  1. years = eval(input("输入年份:" ))
  1. futureInvestmentValue(principal,rate,years)
 
 
 
  1. 输入存款金额: 10000
  2. 输入利率: 0.003
  3. 输入年份:10
  4. 1年内总额10029.999999999998:
  5. 2年内总额10060.089999999997:
  6. 3年内总额10090.270269999995:
  7. 4年内总额10120.541080809995:
  8. 5年内总额10150.902704052423:
  9. 6年内总额10181.35541216458:
  10. 7年内总额10211.899478401072:
  11. 8年内总额10242.535176836274:
  12. 9年内总额10273.262782366783:
  13. 10年内总额10304.082570713881:
 
  • 5
In [1]:
 
 
 
 
 
  1. li = [chr(i) for i in range(ord("A"),ord("Z")+1)]
  1. count=0
  1. for i in li:
  1. print(i,end=' ')
  1. count += 1
  1. if(count%10==0):
  1. print(end='\n')
 
 
 
  1. A B C D E F G H I J
  2. K L M N O P Q R S T
  3. U V W X Y Z
 
  • 6
In [3]:
 
 
 
 
 
  1. import math
  1. def numberOfDaysInAYear():
  1. for i in range(2010,2021):
  1. if i % 4 == 0 and i % 100 != 0 or i % 400 == 0:
  1. print(i,'是366天')
  1. else:
  1. print(i,'是365天')
  1. numberOfDaysInAYear()
 
 
 
  1. 2010 365
  2. 2011 365
  3. 2012 366
  4. 2013 365
  5. 2014 365
  6. 2015 365
  7. 2016 366
  8. 2017 365
  9. 2018 365
  10. 2019 365
  11. 2020 366
 
  • 7
In [1]:
 
 
 
 
 
  1. import numpy as np
  1. import math
  1. def xsj(x1,y1,x2,y2):
  1. p1=np.array([x1,y1])
  1. p2=np.array([x2,y2])
  1. p3=p2-p1
  1. p4=math.hypot(p3[0],p3[1])
  1. print(p4)
  1. x1,y1,x2,y2=map(int,input().split(','))
  1. xsj(x1,y1,x2,y2)
 
 
 
  1. 1,2,3,4
  2. 2.8284271247461903
 
  • 8
In [ ]:
 
 
 
 
 
  1. def a():
  1. for i in range(2, 32):
  1. p = (2 ** i) - 1
  1. print(i,p)
  1. a()
 
 
 
  • 9
In [5]:
 
 
 
 
 
  1. import time
  1. localtime = time.asctime(time.localtime(time.time()))
  1. print("本地时间为 :", localtime)
 
 
 
  1. 本地时间为 : Sun Aug 4 19:00:10 2019
 
  • 10
In [3]:
 
 
 
 
 
  1. import random
  1. random1 = random.randint(1,7)
  1. random2 = random.randint(1,7)
  1. random3 = random.randint(1,7)
  1. total = random1 + random2
  1. print('第一次摇到:{}'.format(random1))
  1. print('第二次摇到:{}'.format(random2))
  1. if total ==7 or total==11:
  1. print('{}+{}={} you win!'.format(random1,random2,total))
  1. elif total ==2 or total==3 or total ==12:
  1. print('{}+{}={} you lose!'.format(random1,random2,total))
  1. elif total==4 or total ==5 or total==6 or total==8 or total==9 or total==10:
  1. total=total+random3
  1. print('第三次摇到:{}'.format(random3))
  1. print('diercihe{}'.format(total))
 
 
 
  1. 第一次摇到:2
  2. 第二次摇到:1
  3. 2+1=3 you lose!
 
  • 11

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

In [4]:
 
 
 
 
 
 
  1. import smtplib
  1. from email.mime.text import MIMEText
  1. def send_mail(username, passwd, recv, title, content, mail_host='smtp.163.com', port=25):
  1. '''
  1. 发送邮件函数,默认使用163smtp
  1. :param username: 邮箱账号 xx@163.com
  1. :param passwd: 邮箱密码
  1. :param recv: 邮箱接收人地址,多个账号以逗号隔开
  1. :param title: 邮件标题
  1. :param content: 邮件内容
  1. :param mail_host: 邮箱服务器
  1. :param port: 端口号
  1. :return:
  1. '''
  1. msg = MIMEText(content) # 邮件内容
  1. msg['Subject'] = title # 邮件主题
  1. msg['From'] = username # 发送者账号
  1. msg['To'] = recv # 接收者账号列表
  1. smtp = smtplib.SMTP(mail_host, port=port) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
  1. smtp.login(username, passwd) # 发送者的邮箱账号,密码
  1. smtp.sendmail(username, recv, msg.as_string())
  1. # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
  1. smtp.quit() # 发送完毕后退出smtp
  1. print('email send success.')
  1. email_user = 'xxxx@163.com' # 发送者账号
  1. email_pwd = 'xxxxx' # 发送者密码
  1. maillist = 'XXX@XXX.com'
  1. title = '测试邮件标题'
  1. content = '这里是邮件内容'
  1. send_mail(email_user, email_pwd, maillist, title, content)
 
 
 
  1. ---------------------------------------------------------------------------
  2. SMTPAuthenticationError Traceback (most recent call last)
  3. <ipython-input-4-240ad3b9e6b5> in <module>
  4. 32 title = '测试邮件标题'
  5. 33 content = '这里是邮件内容'
  6. ---> 34 send_mail(email_user, email_pwd, maillist, title, content)
  7.  
  8. <ipython-input-4-240ad3b9e6b5> in send_mail(username, passwd, recv, title, content, mail_host, port)
  9. 20 msg['To'] = recv # 接收者账号列表
  10. 21 smtp = smtplib.SMTP(mail_host, port=port) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
  11. ---> 22 smtp.login(username, passwd) # 发送者的邮箱账号,密码
  12. 23 smtp.sendmail(username, recv, msg.as_string())
  13. 24 # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
  14.  
  15. D:\anacoda\lib\smtplib.py in login(self, user, password, initial_response_ok)
  16. 728
  17. 729 # We could not login successfully. Return result of last attempt.
  18. --> 730 raise last_exception
  19. 731
  20. 732 def starttls(self, keyfile=None, certfile=None, context=None):
  21.  
  22. D:\anacoda\lib\smtplib.py in login(self, user, password, initial_response_ok)
  23. 719 (code, resp) = self.auth(
  24. 720 authmethod, getattr(self, method_name),
  25. --> 721 initial_response_ok=initial_response_ok)
  26. 722 # 235 == 'Authentication successful'
  27. 723 # 503 == 'Error: already authenticated'
  28.  
  29. D:\anacoda\lib\smtplib.py in auth(self, mechanism, authobject, initial_response_ok)
  30. 640 if code in (235, 503):
  31. 641 return (code, resp)
  32. --> 642 raise SMTPAuthenticationError(code, resp)
  33. 643
  34. 644 def auth_cram_md5(self, challenge=None):
  35.  
  36. SMTPAuthenticationError: (535, b'Error: authentication failed')

Python_4day的更多相关文章

随机推荐

  1. A. Odds and Ends(思维)

    A. Odds and Ends time limit per test 1 second memory limit per test 256 megabytes input standard inp ...

  2. Suitable Replacement

    D. Suitable Replacement 这个题统计出 s 和 t 中的各字母个数以及"?"的个数,直接暴力即可,s中不足的字母可用 "?"来替代 这个题 ...

  3. HDU 5867 Water problem ——(模拟,水题)

    我发这题只是想说明:有时候确实需要用水题来找找自信的~ 代码如下: #include <stdio.h> #include <algorithm> #include <s ...

  4. $\LaTeX$数学公式大全3

    $3\ Delimiters$$|$ |$\vert$ \vert$\|$ \|$\Vert$ \Vert$\{$ \{$\}$ \}$\langle$ \langle$\rangle$ \rangl ...

  5. JAVA中随机生成确定范围内的随机数

    最近工作中的一个业务需要再确定范围内取出一个随机数,网上到时搜出来一堆可以实现的方法,但是鄙人仍是理解不了,虽说已经copy方法直接完成工作了.今天抽时间整理下,希望能够帮助大家更好的理解随机数的实现 ...

  6. Maven :Failed to execute goal on projectt ...: Could not resolve dependencies for project ...

    Maven 项目运行 clean install  之前,先要运行父项目的 clean install, 否则可能出现 Failed to execute goal on project ...: C ...

  7. 图片上传(前端显示预览,后端php接收)

    html: <form action="{:Url('do_ls_law_upload')}" method="POST" accept-charset= ...

  8. 【转】composer proc_open(NUL)报错问题

    composer  执行的时候报错错误信息如下: [ErrorException] proc_open(NUL): failed to open stream: No such file or dir ...

  9. LC 465. Optimal Account Balancing 【lock,hard】

    A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for ...

  10. 转:Zepto的使用以及注意事项

    为什么选择Zepto.js的原因: zepto.js的语法借鉴并且兼容jQuery,会使用jquery就会使用Zepto.js.Zepto.js是移动端的js库.Zepto.js相当于PC端的jQue ...