今日内容
-
三元运算
-
函数
内容详情
1.三元运算(三目运算)
v = 前面 if 条件 else 后面
#让用户输入值,如果值是整数,则转换成整数,否则赋值为none
data = input('>>>')
value =int(data) if data.isdecimal() else None
2.函数
截止目前:面向过程变成。【可读性差/可重用性差】
面向过程编程
user = input('>>>')
if user == '老板'
import smtplib
from email.mime.txt import MIMEText
form email.utils import formataddr
msg = MIMEText('小可爱,猜猜我是谁','plain','utf-8')
msg['From'] = formataddr(['大可爱','248633893@qq.com'])
msg['To'] = formataddr(['小可爱'.763162224@qq.com])
msg['Subject'] = '猜猜我是谁'
server = smtplib('smtp.163.com',25)
server.login('248633893@qq.com','nibushirena')
server.sendmail('248633893@qq.com',['763162224@qq.com',],msg.as.string())
server.quit()
if user == '管理员'
import smtplib
from email.mime.txt import MIMEText
form email.utils import formataddr
msg = MIMEText('小可爱,猜猜我是谁','plain','utf-8')
msg['From'] = formataddr(['大可爱','248633893@qq.com'])
msg['To'] = formataddr(['小可爱'.763162224@qq.com])
msg['Subject'] = '猜猜我是谁'
server = smtplib('smtp.163.com',25)
server.login('248633893@qq.com','nibushirena')
server.sendmail('248633893@qq.com',['763162224@qq.com',],msg.as.string())
server.quit()
2. 函数编程
def_data():
import smtplib
from email.mime.txt import MIMEText
form email.utils import formataddr
msg = MIMEText('小可爱,猜猜我是谁','plain','utf-8')
msg['From'] = formataddr(['大可爱','248633893@qq.com'])
msg['To'] = formataddr(['小可爱'.763162224@qq.com])
msg['Subject'] = '猜猜我是谁'
server = smtplib('smtp.163.com',25)
server.login('248633893@qq.com','nibushirena')
server.sendmail('248633893@qq.com',['763162224@qq.com',],msg.as.string())
server.quit()
user = input('>>>')
if user == '老板':
def_data()
if user == "管理员":
def_data()
对于函数编程:
-
本质:将N行代码拿到别处去并给它起个名字,以后通过名字就可以找到这段代码并执行
-
场景:
-
代码重复执行
-
代码量特别多超过一屏幕,可以选择通过函数进行代码分割
-
-
2.1函数的基本结构
#函数的定义
def 函数名():
#函数内容
pass
函数的执行
函数名()
def_data():
v = [11,22,33,44]
print(v[1])
def_data()
#函数如果不被调用,就永远不会执行
2.2参数
# def get_list_first_data(aaa):
# v = [11,22,33,44]
# print(v[aaa])
# pass
#
# get_list_first_data(0)
练习题
#1.请写一个函数,函数计算列表 info = [11,22,33,44,55]中所有元素的和
def total():
total = 0
index = 0
len_info = len(info)
while index < len_info:
total = total + info[index]
index += 1
print(total)
2.请写出一个函数,函数计算列表中所有元素的和
def sum(a):
data = 0
for item in a:
data += item
print(data)
sun([11,22,33])
3.请写一个函数,函数将两个列表拼接起来
def jion_list(a1,a2):
result = []
result.extend(a1)
result.exxtend(a2)
print(result)
2.3返回值
def total(aaa):
total = 0
for i in aaa:
if type(i) == int:
total += 1
return total
v = total([11,22,44])
print('列表中含有%s个数字' %(v))