1. 元组的元素不可修改,但元组的元素的元素可以被修改。
2. name="eric"
print(name.center(20, "*")
3. list=['a', 'b', 'c', 'd']
str = '-'.join(list)
4. sys.argv 处理参数
maketrans()
语法
maketrans()方法语法:
str.maketrans(intab, outtab)
参数
intab -- 字符串中要替代的字符组成的字符串。
outtab -- 相应的映射字符的字符串。
返回值
返回字符串转换后生成的新字符串。
实例
以下实例展示了使用maketrans() 方法将所有元音字母转换为指定的数字:
#!/usr/bin/python
# -*- coding: UTF-8 -*- from string import maketrans # 必须调用 maketrans 函数。 intab = "aeiou"
outtab = ""
trantab = maketrans(intab, outtab) str = "this is string example....wow!!!";
print(str.translate(trantab));
以上实例输出结果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
作业一:
- 购物商城
- 商品展示,价格
- 买,加入购物车
- 付款,钱不够
python3代码:
一共三个模块: 1. login模块负责登录 2.shopmall模块负责购物功能函数实现 3.shopcart模块为主程序
1. login
import time def login():
input_name = input("Please input your user name : ").strip()
user_lockfile = open("user_lockfile.txt", "r+")
user_file = open("user_file.txt")
user_list = user_file.readlines()
for i in range(3):
input_passwd = input("Please input your password : ").strip()
#查找被锁用户列表判断是否被锁住
if input_name in [locked_user.rstrip() for locked_user in user_lockfile.readlines()]:
print("Sorry, your account is locked!")
user_file.close()
user_lockfile.close()
exit(1)
else: #没有被锁住,查找用户列表
if input_name not in [user_record.split()[0] for user_record in user_list]:
print("Sorry, your account doesn't exist!")
user_file.close()
user_lockfile.close()
exit(2)
else: #用户存在,判断密码是否正确,正确跳出循环
input_record = input_name + ' ' + input_passwd
money = 0
for user_record in user_list:
user_info = user_record.split()[0]+' '+user_record.split()[1]
if input_record == user_info:
#money = int(user_record.split()[2])
print("Logging in...")
time.sleep(1)
user_file.close()
user_lockfile.close()
return input_name
else:#密码不正确,判断错误次数,错误三次(i=2)将用户锁住
if i == 2:
user_lockfile.write(input_name + "\n")
print("Sorry, you're locked!")
user_file.close()
user_lockfile.close()
exit(3)
else:#剩余机会数 2-i
chance = 2 - i
print("Wrong password! %s chances left!" % chance) def get_money(username):
user_file = open("user_file.txt")
for line in user_file.readlines():
if username == line.split()[0]:
money = line.split()[2]
user_file.close()
return money def update_money(username, old, new):
with open("user_file.txt", 'r') as file:
lines = file.readlines()
with open("user_file.txt", 'w') as file:
for line in lines:
if line.split()[0] == username:
line = line.replace(str(old), str(new))
file.write(line)
2. shopmall
import time
import homework3.login as login_module FIRST_LAYER_CHOICE = ''
CART = {}
USERNAME = ''
CART_CHANGE_FLAG = '' def input_verify(choice):
if str.isdigit(choice):
choice = int(choice)
return choice #欢迎界面框架
def framework_show(username='', cart={}):
global USERNAME
USERNAME = username
money = input_verify(login_module.get_money(username))
print('''
#############################################################
* *
* Welcome to Wayne's Shopping Mall *
* *
#############################################################
''', end='')
userstring = "用户:%s\t余额:%d\t购物车:%d" % (username, money, len(cart))
print(userstring.center(50)) #商品总展示框架,一级菜单
def goods_show(goods_dict):
global FIRST_LAYER_CHOICE
print("=============================================================")
print("编号\t名称\t\t\t价格\t\t库存")
print("=============================================================")
for key in goods_dict.keys():
name,price,inventory = goods_dict[key].values()
print("%-4s\t%-12s\t%-4d\t\t%-4d" % (key, name, price, inventory))
print("=============================================================")
goods_input = input("请选择:\t编号(1-%d)|购物车(c)|结账(p)|退出(q) : " % max(key for key in goods_dict.keys()))
goods_input = input_verify(goods_input)
if goods_input == 'q':
exit(0)
elif goods_input == 'c' or goods_input == 'p' or goods_input in goods_dict.keys():
FIRST_LAYER_CHOICE = goods_input
else:
print("输入错误!")
FIRST_LAYER_CHOICE = ''
time.sleep(2) while FIRST_LAYER_CHOICE:
if FIRST_LAYER_CHOICE in goods_dict.keys(): #若选择商品编号,则调用商品信息展示函数
goods_info(FIRST_LAYER_CHOICE, goods_dict)
elif FIRST_LAYER_CHOICE == 'c':
cart_show(goods_dict)
elif FIRST_LAYER_CHOICE == 'p':
pay_show() #选中商品进入二级菜单商品信息展示
def goods_info(choice, goods_dict):
global FIRST_LAYER_CHOICE
name,price,inventory = goods_dict[choice].values()
print("【编号: %s\t名称: %s\t价格: %d(元)\t库存: %d】" % (choice, name, price, inventory))
if inventory == 0:
print("无库存!")
FIRST_LAYER_CHOICE = ''
time.sleep(2)
else:
goods_num_input = input("请输入购买数量(库存%d)|返回(b)|退出(q): " % inventory)
goods_num_input = input_verify(goods_num_input)
if goods_num_input == 'q':
exit(0)
elif goods_num_input == 'b': #若返回,则将全局变量赋值
FIRST_LAYER_CHOICE = ''
elif type(goods_num_input) is int and goods_num_input > 0 and goods_num_input <= inventory: #若输入数量在库存内
add_cart(goods_dict, goods_num_input) #调用添加购物车函数
else:
print("输入错误!")
time.sleep(1) #商品添加购物车功能实现
def add_cart(goods_dict, goods_num):
global FIRST_LAYER_CHOICE
global CART
global USERNAME name, price, inventory = goods_dict[FIRST_LAYER_CHOICE].values()
confirm = input("确认购买%d个<%s>? y/n: " % (goods_num, name))
if confirm == 'n':
FIRST_LAYER_CHOICE = ''
elif confirm == 'y':
inventory = inventory - goods_num
goods_dict[FIRST_LAYER_CHOICE]['inventory'] = inventory #更新库存, 添加购物车不扣余额
if FIRST_LAYER_CHOICE in CART.keys(): #若购物车中存在该商品,直接修改数量,否则添加至购物车
CART[FIRST_LAYER_CHOICE]['num'] += goods_num
else:
CART[FIRST_LAYER_CHOICE] = {'name':name, 'price':price,'num':goods_num}
print("添加购物车成功!")
FIRST_LAYER_CHOICE = ''
else:
print("输入错误!")
#return cart_dict def cart_show(goods_dict):
global CART
global FIRST_LAYER_CHOICE
global CART_CHANGE_FLAG
print('''
-------------------------------------------------------------
* Shopcart *
-------------------------------------------------------------
编号\t物品\t\t\t单价\t\t数量''')
for i in sorted([i for i in CART.keys()]):
name = CART[i]['name']
price = CART[i]['price']
num = CART[i]['num']
print("%-8d%-12s\t%-4d\t\t%-4d" % (i, name, price, num))
print("-------------------------------------------------------------")
CART_CHANGE_FLAG = input("请选择 修改(c)|结账(p)|返回(b)|退出(q) : ")
if CART_CHANGE_FLAG == 'q': exit(0)
elif CART_CHANGE_FLAG == 'b':
FIRST_LAYER_CHOICE = ''
elif CART_CHANGE_FLAG == 'p':
pay_show()
elif CART_CHANGE_FLAG == 'c':
while CART_CHANGE_FLAG: #循环修改商品,直到用户在修改商品界面选b返回
cart_modify(goods_dict)
else:
print("输入错误!") def cart_modify(goods_dict):
global CART
global FIRST_LAYER_CHOICE
global CART_CHANGE_FLAG
if CART == {}: #若购物车为空,返回选购商品
print("购物车为空!请选购商品!")
time.sleep(1)
FIRST_LAYER_CHOICE = ''
CART_CHANGE_FLAG = ''
else:
print('''
-------------------------------------------------------------
* Shopcart *
-------------------------------------------------------------
编号\t物品\t\t\t单价\t\t数量''')
for i in sorted([i for i in CART.keys()]):
name = CART[i]['name']
price = CART[i]['price']
num = CART[i]['num']
print("%-8d%-12s\t%-4d\t\t%-4d" % (i, name, price, num))
print("-------------------------------------------------------------")
change_choice = input("请输入要修改的商品编号, 返回<b>: ")
change_choice = input_verify(change_choice)
if change_choice == 'b':
CART_CHANGE_FLAG = ''
else:
if change_choice not in CART.keys():
print("输入错误!")
else:
name, price, num = CART[change_choice].values()
print("【编号: %s\t名称: %s\t价格: %d(元)\t数量: %d】" % (change_choice, name, price, num))
inventory_total = goods_dict[change_choice]['inventory'] + num #由于没付款,这里显示 总库存=当前库存+购物车数量
change_num = input("请输入要购买的数量, 库存%d: " % inventory_total)
change_num = input_verify(change_num)
if change_num in range(1,inventory_total+1):
confirm = input("确认购买%d个<%s>? y/n: " % (change_num, name))
if confirm == 'y':
CART[change_choice]['num'] = change_num
inventory = inventory_total - change_num #修改当前库存为 总库存-修改后的购物车数量
goods_dict[change_choice]['inventory'] = inventory
elif confirm == 'n':
pass
else:
print("输入错误!")
elif change_num == 0:
confirm = input("确认从购物车清除<%s>? y/n: " % name)
if confirm == 'y':
CART.pop(change_choice) #从购物车清除后,显示当前库存为总库存
goods_dict[change_choice]['inventory'] = inventory_total
if CART == {}:
CART_CHANGE_FLAG = ''
elif confirm == 'n':
pass
else:
print("输入错误!")
else:
print("输入错误!") def pay_show():
global USERNAME
global CART
global FIRST_LAYER_CHOICE
if CART == {}:
print("购物车为空!请选购商品!")
time.sleep(1)
FIRST_LAYER_CHOICE = ''
else:
total_price = 0
print("*************************************************************")
print("%-8s%-12s%-8s%-8s" % ("编号", "商品", "数量", "总价"))
for i in CART.keys():
name = CART[i]['name']
num = CART[i]['num']
price = CART[i]['price']
goods_price = num * price
total_price += goods_price
print("%-10d%-14s%-10d%-4d" % (i, name, num, goods_price))
print("*************************************************************")
money = input_verify(login_module.get_money(USERNAME))
print("购物车总价 : %d\t|\t当前余额 : %d" % (total_price, money))
if money < total_price: #若用余额不足以支付购物车,提示并返回
print("余额不足!请充值!")
time.sleep(1)
FIRST_LAYER_CHOICE = 'c' if FIRST_LAYER_CHOICE == 'c' else ''
else:
pay__input = input("确认购买上述物品? y/n : ")
if pay__input == 'y':
left = money - total_price
login_module.update_money(USERNAME, money, left)
print("付款成功! 余额 %d 元。" % left)
time.sleep(1)
exit(0)
elif pay__input == 'n':
FIRST_LAYER_CHOICE = 'c' if FIRST_LAYER_CHOICE == 'c' else ''
else:
print("输入错误!") def purchase(username, goods_dict):
while True:
framework_show(username)
goods_show(goods_dict)
3. shopcart
import homework3.login as login_module
import homework3.shopmall as shopmall GOODS = {1:{'name':'iphone8', 'price':6888, 'inventory':30},
2:{'name':'iphoneX', 'price':8388, 'inventory':8},
3:{'name':'ipad mini4', 'price':2888, 'inventory':20},
4:{'name':'MI MIX2', 'price':3288, 'inventory':25},
5:{'name':'MEIZU Pro8', 'price':2488, 'inventory':2}} if __name__ == "__main__":
username = login_module.login()
shopmall.purchase(username, GOODS)
4. 用户信息记录文件
wayne 123 1999829036
kevin 123 20000
root shroot123 3000
5. 用户锁定记录文件
kevin
james