今日內容
- 三元運算
- 函式
內容詳細
-
三元運算(三目運算)
v = 前面 if 條件 else 后面
if 條件:
v = '前面'
else:
v = '后面'讓用戶輸入值,如果值是整數,則轉換成整數,否則賦值為None
data = https://www.cnblogs.com/cuiyongchao007/p/input('>>>')
value = https://www.cnblogs.com/cuiyongchao007/p/int(data) if data.isdecimal() else None
注意:先做出來,再思考如何簡化,
- 函式
截至目前:面向程序編程, 【可讀性差/可重用性差】,
# 面向程序編程
user_input = input('請輸入角色:')
if user_input == '管理員':
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('管理員,我想演男一號,你想怎么著都行,', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["管理員", '[email protected]'])
msg['Subject'] = "情愛的導演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['管理員', ], msg.as_string())
server.quit()
elif user_input == '業務員':
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('業務員,我想演男一號,你想怎么著都行,', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["業務員", '業務員'])
msg['Subject'] = "情愛的導演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['業務員', ], msg.as_string())
server.quit()
elif user_input == '老板':
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('老板,我想演男一號,你想怎么著都行,', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["老板", '老板郵箱'])
msg['Subject'] = "情愛的導演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['老板郵箱', ], msg.as_string())
server.quit()
函式式編程
def send_email():
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('老板,我想演男一號,你想怎么著都行,', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["老板", '老板郵箱'])
msg['Subject'] = "情愛的導演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', ['老板郵箱', ], msg.as_string())
server.quit()
user_input = input('請輸入角色:')
if user_input == '管理員':
send_email()
elif user_input == '業務員':
send_email()
elif user_input == '老板':
send_email()
對于函式編程:
- 本質:將N行代碼拿到別處并給他起個名字,以后通過名字就可以找到這段代碼并執行,
- 場景:
- 代碼重復執行,
- 代碼量特別多超過一屏,可以選擇通過函式進行代碼的分割,
2.1 函式的基本結構
# 函式的定義
def 函式名():
# 函式內容
pass
# 函式的執行
函式名()
def get_list_first_data():
v = [11,22,33,44]
print(v[0])
get_list_first_data()
# 注意:函式如果不被呼叫,則內部代碼永遠不會被執行,
# 假如:管理員/業務員/老板用的是同一個郵箱,
def send_email():
print('發送郵件成功,假設有10含代碼')
user_input = input('請輸入角色:')
if user_input == '管理員':
send_email()
elif user_input == '業務員':
send_email()
elif user_input == '老板':
send_email()
2.2 引數
def get_list_first_data(aaa): # aaa叫形式引數(形參)
v = [11,22,33,44]
print(v[aaa])
get_list_first_data(1) # 2/2/1呼叫函式時傳遞叫:實際引數(實參)
get_list_first_data(2)
get_list_first_data(3)
get_list_first_data(0)
# 假如:管理員/業務員/老板用的是同一個郵箱,
"""
def send_email(to):
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('導演,我想演男一號,你想怎么著都行,', 'plain', 'utf-8')
msg['From'] = formataddr(["李邵奇", '[email protected]'])
msg['To'] = formataddr(["導演", to])
msg['Subject'] = "情愛的導演"
server = smtplib.SMTP("smtp.163.com", 25)
server.login("[email protected]", "qq1105400511")
server.sendmail('[email protected]', [to, ], msg.as_string())
server.quit()
"""
def send_email(to):
template = "要給%s發送郵件" %(to,)
print(template)
user_input = input('請輸入角色:')
if user_input == '管理員':
send_email('[email protected]')
elif user_input == '業務員':
send_email('[email protected]')
elif user_input == '老板':
send_email('[email protected]')
練習題
# 1. 請寫一個函式,函式計算串列 info = [11,22,33,44,55] 中所有元素的和,
def get_sum():
info = [11,22,33,44,55]
data = https://www.cnblogs.com/cuiyongchao007/p/0
for item in info:
data += item
print(data)
get_sum()
# 2. 請寫一個函式,函式計算串列中所有元素的和,
def get_list_sum(a1):
data = 0
for item in a1:
data += item
print(data)
get_list_sum([11,22,33])
get_list_sum([99,77,66])
v1 = [8712,123,123]
get_list_sum(v1)
# 3. 請寫一個函式,函式將兩個串列拼接起來,
def join_list(a1,a2):
result = []
result.extend(a1)
result.extend(a2)
print(result)
join_list([11,22,33],[55,66,77])
# 4. 計算一個串列的長度
def my_len(arg):
count = 0
for item in arg:
count += 1
print(count)
v = [11,22,33]
my_len(v)
len(v)
# 5. 發郵件的示例
def send_email(role,to):
template = "要給%s%s發送郵件" %(role,to,)
print(template)
user_input = input('請輸入角色:')
if user_input == '管理員':
send_email('管理員','[email protected]')
elif user_input == '業務員':
send_email('業務員','[email protected]')
elif user_input == '老板':
send_email('老板','[email protected]')
2.3 回傳值
def func(arg):
# ....
return 9 # 回傳值為9 默認:return None
val = func('adsfadsf')
# 1. 讓用戶輸入一段字串,計算字串中有多少A字符的個數,有多少個就在檔案a.txt中寫多少個“李邵奇”,
def get_char_count(data):
sum_counter = 0
for i in data:
if i == 'A':
sum_counter += 1
return sum_counter
def write_file(line):
if len(line) == 0:
return False # 函式執行程序中,一旦遇到return,則停止函式的執行,
with open('a.txt',mode='w',encoding='utf-8') as f:
f.write(line)
return True
content = input('請輸入:')
counter = get_char_count(content)
write_data = https://www.cnblogs.com/cuiyongchao007/p/"李邵奇" * counter
status = write_file(write_data)
if status:
print('寫入成功')
else:
print('寫入失敗')
2.4 上述總結
# 情況1
def f1():
pass
f1()
# 情況2
def f2(a1):
pass
f2(123)
# 情況3
def f3():
return 1
v1 = f3()
# 情況4
def f4(a1,a2):
# ...
return 999
v2 = f4(1,7)
2.5 練習題
# 1. 寫函式,計算一個串列中有多少個數字,列印: 串列中有%s個數字,
# 提示:type('x') == int 判斷是否是數字,
"""
# 方式一:
def get_list_counter1(data_list):
count = 0
for item in data_list:
if type(item) == int:
count += 1
msg = "串列中有%s個數字" %(count,)
print(msg)
get_list_counter1([1,22,3,'alex',8])
# 方式二:
def get_list_counter2(data_list):
count = 0
for item in data_list:
if type(item) == int:
count += 1
return count
v = get_list_counter1([1,22,3,'alex',8])
msg = "串列中有%s個數字" %(v,)
print(msg)
"""
# 2. 寫函式,計算一個串列中偶數索引位置的資料構造成另外一個串列,并回傳,
"""
# 方式一:
def get_data_list1(arg):
v = arg[::2]
return v
data = https://www.cnblogs.com/cuiyongchao007/p/get_data_list1([11,22,33,44,55,66])
# 方式二:
def get_data_list2(arg):
v = []
for i in range(0,len(arg)):
if i % 2 == 0:
v.append(arg[i])
return v
data = get_data_list2([11,22,33,44,55,66])
"""
# 3. 讀取檔案,將檔案的內容構造成指定格式的資料,并回傳,
"""
a.log檔案
alex|123|18
eric|uiuf|19
...
目標結構:
a. ["alex|123|18","eric|uiuf|19"] 并回傳,
b. [['alex','123','18'],['eric','uiuf','19']]
c. [
{'name':'alex','pwd':'123','age':'18'},
{'name':'eric','pwd':'uiuf','age':'19'},
]
"""
def info_lista():
a_list=[]
with open('a.log',mode='r',encoding='utf-8') as f1:
for line in f1:
a_list.append(line.strip())
print(a_list)
info_lista()
def info_listb():
b_list=[]
B_list=[]
with open('a.log',mode='r',encoding='utf-8') as f1:
for line in f1:
b_list.append(line.strip().split('|'))
for i in range(len(b_list)):
B_list.append(b_list[i])
print(B_list)
info_listb()
def info_listc():
C_list=[]
stand=['name','pwd','age']
with open('a.log',mode='r',encoding='utf-8') as f1:
for line in f1:
c_list = []
C = {}
c_list=line.strip().split('|')
C[stand[0]] = c_list[0]
C[stand[1]] = c_list[1]
C[stand[2]] = c_list[2]
C_list.append(C)
print(C_list)
info_listc()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/3843.html
標籤:其他
上一篇:前端面試積累(整理中)
