函数
- 函数可以用来定义可重复代码,组织和简化
- 一般来说一个函数在实际开发中为一个小功能
- 一个类为一个大功能
- 同样函数的长度不要超过一屏
Python中的所有函数实际上都是有返回值(return None),
如果你没有设置return,那么Python将不显示None.
如果你设置return,那么将返回出return这个值.
def HJN():
print('Hello')
return 1000
b=HJN()
print(b)
HJN
def panduan(number):
if number % 2 == 0:
print('O')
else:
print('J')
panduan(number=1)
panduan(2)
定义一个函数
def function_name(list of parameters):
do something
- 以前使用的random 或者range 或者print.. 其实都是函数或者类
函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.
import random
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()
- "()" 就代表调用
def H():
print('hahaha')
def B():
H()
B()
def A(f):
f()
A(B)
带返回值和不带返回值的函数
- return 返回的内容
- return 返回多个值
- 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
- 当然也可以自定义返回None
EP:
def main():
print(min(min(5,6),(51,6)))
def min(n1,n2):
a = n1
if n2 < a:
a = n2
main()
类型和关键字参数
- 普通参数
- 多个参数
- 默认值参数
- 不定长参数
普通参数
多个参数
默认值参数
强制命名
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
U('HJi12')
不定长参数
- *args
- 不定长,来多少装多少,不装也是可以的
- 返回的数据类型是元组
- args 名字是可以修改的,只是我们约定俗成的是args
- **kwargs
- 返回的字典
- 输入的一定要是表达式(键值对)
- name,*args,name2,**kwargs 使用参数名
def TT(a,b)
def TT(*args,**kwargs):
print(kwargs)
print(args)
TT(1,2,3,4,6,a=100,b=1000)
{'key':'value'}
TT(1,2,4,5,7,8,9,)
def B(name1,nam3):
pass
B(name1=100,2)
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,'还未开放')
sum_(-1,0,1,4,A='var')
'aHbK134'.__iter__
b = 'asdkjfh'
for i in b :
print(i)
2,5
2 + 22 + 222 + 2222 + 22222
变量的作用域
- 局部变量 local
- 全局变量 global
- globals 函数返回一个全局变量的字典,包括所有导入的变量
- locals() 函数会以字典类型返回当前位置的全部局部变量。
a = 1000
b = 10
def Y():
global a,b
a += 100
print(a)
Y()
def YY(a1):
a1 += 100
print(a1)
YY(a)
print(a)
注意:
- 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
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)
- 2
def sumDigits(i):
ge=i%10
shi=i//10%10
bai=i//100
sum=ge + shi +bai
print(sum)
sumDigits(234)
- 3
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)
- 4
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)
- 5
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'))
- 6
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)
- 7
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)
- 8
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()
- 9
import time
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
2019 - 1970
- 10
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()
- 11
去网上寻找如何用Python代码发送邮件
# 简单邮件传输协议
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这个值.
def HJN():
print('Hello')
return 1000
b=HJN()
print(b)
HJN
def panduan(number):
if number % 2 == 0:
print('O')
else:
print('J')
panduan(number=1)
panduan(2)
定义一个函数
def function_name(list of parameters):
do something
- 以前使用的random 或者range 或者print.. 其实都是函数或者类
函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.
import random
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()
- "()" 就代表调用
def H():
print('hahaha')
def B():
H()
B()
def A(f):
f()
A(B)
带返回值和不带返回值的函数
- return 返回的内容
- return 返回多个值
- 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
- 当然也可以自定义返回None
EP:
def main():
print(min(min(5,6),(51,6)))
def min(n1,n2):
a = n1
if n2 < a:
a = n2
main()
类型和关键字参数
- 普通参数
- 多个参数
- 默认值参数
- 不定长参数
普通参数
多个参数
默认值参数
强制命名
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
U('HJi12')
不定长参数
- *args
- 不定长,来多少装多少,不装也是可以的
- 返回的数据类型是元组
- args 名字是可以修改的,只是我们约定俗成的是args
- **kwargs
- 返回的字典
- 输入的一定要是表达式(键值对)
- name,*args,name2,**kwargs 使用参数名
def TT(a,b)
def TT(*args,**kwargs):
print(kwargs)
print(args)
TT(1,2,3,4,6,a=100,b=1000)
{'key':'value'}
TT(1,2,4,5,7,8,9,)
def B(name1,nam3):
pass
B(name1=100,2)
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,'还未开放')
sum_(-1,0,1,4,A='var')
'aHbK134'.__iter__
b = 'asdkjfh'
for i in b :
print(i)
2,5
2 + 22 + 222 + 2222 + 22222
变量的作用域
- 局部变量 local
- 全局变量 global
- globals 函数返回一个全局变量的字典,包括所有导入的变量
- locals() 函数会以字典类型返回当前位置的全部局部变量。
a = 1000
b = 10
def Y():
global a,b
a += 100
print(a)
Y()
def YY(a1):
a1 += 100
print(a1)
YY(a)
print(a)
注意:
- 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
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)
- 2
def sumDigits(i):
ge=i%10
shi=i//10%10
bai=i//100
sum=ge + shi +bai
print(sum)
sumDigits(234)
- 3
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)
- 4
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)
- 5
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'))
- 6
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)
- 7
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)
- 8
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()
- 9
import time
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
2019 - 1970
- 10
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()
- 11
去网上寻找如何用Python代码发送邮件
# 简单邮件传输协议
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这个值.
def HJN():
print('Hello')
return 1000
b=HJN()
print(b)
HJN
def panduan(number):
if number % 2 == 0:
print('O')
else:
print('J')
panduan(number=1)
panduan(2)
定义一个函数
def function_name(list of parameters):
do something
- 以前使用的random 或者range 或者print.. 其实都是函数或者类
函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.
import random
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()
- "()" 就代表调用
def H():
print('hahaha')
def B():
H()
B()
def A(f):
f()
A(B)
带返回值和不带返回值的函数
- return 返回的内容
- return 返回多个值
- 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
- 当然也可以自定义返回None
EP:
def main():
print(min(min(5,6),(51,6)))
def min(n1,n2):
a = n1
if n2 < a:
a = n2
main()
类型和关键字参数
- 普通参数
- 多个参数
- 默认值参数
- 不定长参数
普通参数
多个参数
默认值参数
强制命名
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
U('HJi12')
不定长参数
- *args
- 不定长,来多少装多少,不装也是可以的
- 返回的数据类型是元组
- args 名字是可以修改的,只是我们约定俗成的是args
- **kwargs
- 返回的字典
- 输入的一定要是表达式(键值对)
- name,*args,name2,**kwargs 使用参数名
def TT(a,b)
def TT(*args,**kwargs):
print(kwargs)
print(args)
TT(1,2,3,4,6,a=100,b=1000)
{'key':'value'}
TT(1,2,4,5,7,8,9,)
def B(name1,nam3):
pass
B(name1=100,2)
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,'还未开放')
sum_(-1,0,1,4,A='var')
'aHbK134'.__iter__
b = 'asdkjfh'
for i in b :
print(i)
2,5
2 + 22 + 222 + 2222 + 22222
变量的作用域
- 局部变量 local
- 全局变量 global
- globals 函数返回一个全局变量的字典,包括所有导入的变量
- locals() 函数会以字典类型返回当前位置的全部局部变量。
a = 1000
b = 10
def Y():
global a,b
a += 100
print(a)
Y()
def YY(a1):
a1 += 100
print(a1)
YY(a)
print(a)
注意:
- 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
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)
- 2
def sumDigits(i):
ge=i%10
shi=i//10%10
bai=i//100
sum=ge + shi +bai
print(sum)
sumDigits(234)
- 3
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)
- 4
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)
- 5
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'))
- 6
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)
- 7
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)
- 8
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()
- 9
import time
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
2019 - 1970
- 10
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()
- 11
去网上寻找如何用Python代码发送邮件
# 简单邮件传输协议
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这个值.
def HJN():
print('Hello')
return 1000
b=HJN()
print(b)
HJN
def panduan(number):
if number % 2 == 0:
print('O')
else:
print('J')
panduan(number=1)
panduan(2)
定义一个函数
def function_name(list of parameters):
do something
- 以前使用的random 或者range 或者print.. 其实都是函数或者类
函数的参数如果有默认值的情况,当你调用该函数的时候: 可以不给予参数值,那么就会走该参数的默认值 否则的话,就走你给予的参数值.
import random
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()
- "()" 就代表调用
def H():
print('hahaha')
def B():
H()
B()
def A(f):
f()
A(B)
带返回值和不带返回值的函数
- return 返回的内容
- return 返回多个值
- 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值
- 当然也可以自定义返回None
EP:
def main():
print(min(min(5,6),(51,6)))
def min(n1,n2):
a = n1
if n2 < a:
a = n2
main()
类型和关键字参数
- 普通参数
- 多个参数
- 默认值参数
- 不定长参数
普通参数
多个参数
默认值参数
强制命名
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
U('HJi12')
不定长参数
- *args
- 不定长,来多少装多少,不装也是可以的
- 返回的数据类型是元组
- args 名字是可以修改的,只是我们约定俗成的是args
- **kwargs
- 返回的字典
- 输入的一定要是表达式(键值对)
- name,*args,name2,**kwargs 使用参数名
def TT(a,b)
def TT(*args,**kwargs):
print(kwargs)
print(args)
TT(1,2,3,4,6,a=100,b=1000)
{'key':'value'}
TT(1,2,4,5,7,8,9,)
def B(name1,nam3):
pass
B(name1=100,2)
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,'还未开放')
sum_(-1,0,1,4,A='var')
'aHbK134'.__iter__
b = 'asdkjfh'
for i in b :
print(i)
2,5
2 + 22 + 222 + 2222 + 22222
变量的作用域
- 局部变量 local
- 全局变量 global
- globals 函数返回一个全局变量的字典,包括所有导入的变量
- locals() 函数会以字典类型返回当前位置的全部局部变量。
a = 1000
b = 10
def Y():
global a,b
a += 100
print(a)
Y()
def YY(a1):
a1 += 100
print(a1)
YY(a)
print(a)
注意:
- 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
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)
- 2
def sumDigits(i):
ge=i%10
shi=i//10%10
bai=i//100
sum=ge + shi +bai
print(sum)
sumDigits(234)
- 3
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)
- 4
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)
- 5
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'))
- 6
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)
- 7
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)
- 8
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()
- 9
import time
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
2019 - 1970
- 10
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()
- 11
去网上寻找如何用Python代码发送邮件
# 简单邮件传输协议
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()