2-4 函數練習題
阿新 • • 發佈:2018-03-05
清空 elif write dex read function div isdigit 選項
練習題
修改個人信息程序
在一個文件裏存多個人的個人信息,如以下
username password age position department
alex abc123 24 Engineer IT
rain df2@432 25 Teacher Teching
....
1.輸入用戶名密碼,正確後登錄系統 ,打印
1. 修改個人信息
2. 打印個人信息
3. 修改密碼
2.每個選項寫一個方法
3.登錄時輸錯3次退出程序
練習題答案
def print_personal_info(account_dic,username):
"""
print user info
:param account_dic: all account‘s data
:param username: username
:return: None
"""
person_data = account_dic[username]
info = ‘‘‘
------------------
Name: %s
Age : %s
Job : %s
Dept: %s
Phone: %s
------------------
‘‘‘ %(person_data[1],
person_data[2],
person_data[3],
person_data[4],
person_data[5],
)
print(info)
def save_back_to_file(account_dic):
"""
把account dic 轉成字符串格式 ,寫回文件
:param account_dic:
:return:
"""
f.seek(0) #回到文件頭
f.truncate() #清空原文件
for k in account_dic:
row = ",".join(account_dic[k])
f.write("%s\n"%row)
f.flush()
def change_personal_info(account_dic,username):
"""
change user info ,思路如下
1. 把這個人的每個信息打印出來, 讓其選擇改哪個字段,用戶選擇了的數字,正好是字段的索引,這樣直接 把字段找出來改掉就可以了
2. 改完後,還要把這個新數據重新寫回到account.txt,由於改完後的新數據 是dict類型,還需把dict轉成字符串後,再寫回硬盤
:param account_dic: all account‘s data
:param username: username
:return: None
"""
person_data = account_dic[username]
print("person data:",person_data)
column_names = [‘Username‘,‘Password‘,‘Name‘,‘Age‘,‘Job‘,‘Dept‘,‘Phone‘]
for index,k in enumerate(person_data):
if index >1: #0 is username and 1 is password
print("%s. %s: %s" %( index, column_names[index],k) )
choice = input("[select column id to change]:").strip()
if choice.isdigit():
choice = int(choice)
if choice > 0 and choice < len(person_data): #index不能超出列表長度邊界
column_data = person_data[choice] #拿到要修改的數據
print("current value>:",column_data)
new_val = input("new value>:").strip()
if new_val:#不為空
person_data[choice] = new_val
print(person_data)
save_back_to_file(account_dic) #改完寫回文件
else:
print("不能為空。。。")
account_file = "account.txt"
f = open(account_file,"r+")
raw_data = f.readlines()
accounts = {}
#把賬戶數據從文件裏讀書來,變成dict,這樣後面就好查詢了
for line in raw_data:
line = line.strip()
if not line.startswith("#"):
items = line.split(",")
accounts[items[0]] = items
menu = ‘‘‘
1. 打印個人信息
2. 修改個人信息
3. 修改密碼
‘‘‘
count = 0
while count <3:
username = input("Username:").strip()
password = input("Password:").strip()
if username