首页 > 技术文章 > 基本数据类型重点作业

newt 2018-05-15 20:28 原文

---恢复内容开始---

#实现用户输入用户名和密码,当用户名为 seven 或 alex 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次
s = 3
while s>0:
    name = input("请输入用户名:").strip()
    password = input("请输入密码:").strip()
    if name == "seven" or name == "alex" and password =="123":
        print("登录成功")
        break
    else:
        print("登录失败,你还有%s次机会" %s)
        s -= 1
#使用 while 循环实现输出 2 -3 + 4-5 + 6 ... + 100的和
sum = 0
a = 2
while a<=100:
    if a%2==0:
        sum += a
    else:
        sum -= a
    a += 1
print(sum)
#使用 for 循环和 range 实现输的1 -2 + 3-4 + 5-6 ... + 99的和
sum = 0
for i in range(100):
    if i % 2 == 0:
        sum -= i
    else:
        sum += i
print(sum)
#使用 while 循环实现输出  1,2,3,4,5,7,8,9,11,12
a = 1
while a<13:
    print(a)
    a += 1
#使用 while 循环实现输出 1-100 内的所有奇数
a = 1
while a <= 100:
    if a % 2 == 0:
        pass
    else:
        print(a)
    a += 1
#分别书写数字 5,10,32,7 的二进制表示
for i in [5,10,32,7]:
    print("{}的二进制数是{}".format(i,bin(i)))
    print("%s的二进制数是%s" %(i, bin(i)))
#输入一年份,判断该年份是否是闰年并输出结果。(编程题)
#注:凡符合下面两个条件之一的年份是闰年。 (1) 能被4整除但不能被100整除。 (2) 能被400整除。
year = input("请输入您需要查询的年份:").strip()
year = int(year)

if year % 4 == 0 and year % 100 != 0 or year % 400 ==0:
    print("%d是闰年" %year)
#编写登陆接口
# 基础需求:
# 让用户输入用户名密码
# 认证成功后显示欢迎信息
# 输错三次后退出程序

count = 3
while count > 0:
    name = input("帐号:")
    password = input("密码:")
    if name == "long" and password == "123":
        print("欢迎登录")
        break
    else:
        count -= 1
        print("登录失败,你还有%d次机会" %count)
#如有一个变量n1 = 5,请使用int提供的方法,得到该变量最少可以用多少个二进制位表示?
n1 = 5
print(int.bit_length(n1))
#判断name变量对应的值是否以"al"开头,并输出结果

name=" aleX"
print(name.startswith("al"))
#将name变量对应的值中的"l"替换为"p",并输出结果
name=" aleX"
print(name.replace("l","p"))
#请输出name变量对应的值的后2个字符?
name=" aleX"
print(name[-2:])  #-1代表最后一个字符,-2代表倒数第二个字符
#获取子序列,仅不包含最后一个字符。如:oldboy 则获取oldbo;root则获取roo
name=" aleX"
print(name.rstrip(name[-1:]))
#利用下划线将列表的每一个元素拼接成字符串,li = "alexericrain"
li = "alexericrain"
print("_".join(li))
#计算用户输入的内容中有几个十进制数?几个字母?
#如:
#content=input('请输入内容:') #如: asduiaf878123jkjsfd-213928
content = input('请输入内容:') .strip()  #一定要记得使用strip去除空格
v,r = content.split("+")
print(int(v)+int(r))
#计算用户输入的内容中有几个十进制数?几个字母?
# 如:
# content=input('请输入内容:') #如: asduiaf878123jkjsfd-213928
content=input('请输入内容:').strip()
v = 0
s = 0
for i in content:
    if i.isdecimal():
        v += 1
    if i.isalpha():
        s += 1
    else:
        pass
print("数字的个数是%d,字母的个数是%d" %(v,s))
while True:
    name = input("请输入用户名:")
    if name == "q" or name == "Q":
        break
    if len(name) <= 20:
        pass
    else:
        name = name[:20]
    password = input("请输入密码:")
    if password == "q" or password == "Q":
        break
    if len(password) <= 20:
        pass
    else:
        password = password[:20]
    email = input("请输入邮箱:")
    if email == "q" or email == "Q":
        break
    if len(email) <= 20:
        pass
    else:
        email = email[:20]
    template = "{0}\t{1}\t{2}\n"
    v = template.format(name,password,email)
    break
print(v.expandtabs(20))  #将\t以及\n转化为空格或者回车
#往names列表里black_girl前面插入一个alex
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
names.insert(names.index("black_girl"),"alex") #占有原来的位置
print(names)
#把shanshan的名字改成中文,姗姗
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
names[names.index("shanshan")] = "姗姗"
print(names)
#往names列表里rain的后面插入一个子列表,["oldboy","oldgirl"]
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
names.insert(names.index("rain")+1,["oldboy","oldgirl"])
print(names)
#创建新列表[1,2,3,4,2,5,6,2],合并入names列表
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
names.extend([1,2,3,4,5,6,2])
print(names)
#.取出names列表中索引2-10的元素,步长为2
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
print(names[2:10:2])
#循环names列表,打印每个元素的索引值,和元素
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
for index,name in enumerate(names):
    print("%s,%s" %(index,name))
#循环names列表,打印每个元素的索引值,和元素,当索引值为偶数时,把对应的元素改为-1
names = ["old_driver","rain","jack","shanshan","peiqi","black_girl"]
for index,name in enumerate(names):
    if index % 2 == 0:
        name = "-1"
    else:
        pass
    print(index,name)
#这一题没理解
#
names里有3个2,请返回第2个2的索引值。不要人肉数,要动态找(提示,找到第一个2的位置,在次基础上再找第2个) print(names.index(2,names.index(2)+1))

 

#查找列表(或元祖或字典)中元素,移除每个元素的空格,并查找以 a 或 A 开头 并且以 c 结尾的所有元素
# li = ["alec", " aric", "Alex", "Tony", "rain"]
# tu = ("alec", " aric", "Alex", "Tony", "rain")
# dic = {'k1': "alex", 'k2': ' aric',"k3": "Alex", "k4": "Tony"}
li = ["alec", " aric", "Alex", "Tony", "rain"]
for i in li:
    i = i.strip()
    c_a = i.startswith("a")
    c_A = i.startswith("A")
    c_c = i.endswith("d")
    if c_a or c_A and c_c:
        print(i)

tu = ("alec", " aric", "Alex", "Tony", "rain")
for i in tu:
    i = i.strip()
    c_a = i.startswith("a")
    c_A = i.startswith("A")
    c_c = i.endswith("d")
    if c_a or c_A and c_c:
        print(i)

dic = {'k1': "alex", 'k2': ' aric',"k3": "Alex", "k4": "Tony"}
for i in dic:
    i = i.strip()
    c_a = i.startswith("a")
    c_A = i.startswith("A")
    c_c = i.endswith("d")
    if c_a or c_A and c_c:
        print(i)
#列表中追加元素 “seven”,并输出添加后的列表
li = ['alex','eric','rain']
li.append("seven")
print(li)
#请在列表的第 1 个位置插入元素 “Tony”,并输出添加后的列表 
li = ['alex','eric','rain']
li.insert(0,"Tony")  #append是追加 insert是在指定位置添加
print(li)
# 写代码,有如下字典,按照要求实现每一个功能,dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
# 请循环输出所有的 key
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
for i in dic.keys():
    print(i)
# 请循环输出所有的 key 和 value
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
for i in dic.keys():
    print(i,dic[i])
# 请在字典中添加一个键值对,'k4':'v4',输出添加后的字典
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic['k4'] = 'v4' #通过索引添加
print(dic)

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic.update({'k4':'v4'}) # 传一个字典
print(dic)

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic.update(k4 = "v4") # 传关键字
print(dic)

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic.update(zip(['k4'],['v4'])) # 传一个zip函数
print(dic)

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic.update([('k4','v4')]) # 传一个包含一个或多个元祖的列表
print(dic)
# 请在k3对应的值中追加一个元素44,输出修改后的字典
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic["k3"].append("44")
print(dic)
# 请在k3对应的值的第1个位置插入个元素18,输出修改后的字典
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic["k3"].insert(0,18)
print(dic)
#请删除字典中键值对,'k1':'v1',并输出删除后的字典
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic.pop("k1")
print(dic)

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
del dic['k1']
print(dic)
#请删除字典中的键'k5'对应的键值对,如果字典中不存在键'k5',则不报错,并且让其返回 None
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
pop_k5=dic.pop("k5","None")
print(pop_k5)
#请获取字典中'k2'对应的值
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
view_k2=dic["k2"]
print(view_k2)

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
view_k2=dic.get("k2")
print(view_k2)
#现有 dic2 = {'k1':'v111','a':'b'}通过一行操作使 dic2 = {'k1':'v1','k2':'v2','k3':'v3','a','b'}
dic2 = {'k1':'v111','a':'b'}
dic2.update({"k1":"v1","k2":"v2","k3":"v3"})
print(dic2)
# lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
# 将列表 lis 中的'tt'变成大写(用两种方式)
lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
view_lis_tt = lis[0][1][2]["k1"]
view_tt = lis[0][1][2]["k1"][0]
view_lis_tt[0] = view_tt.upper()
print(lis)
# 将列表中的数字 3 变成 字符串 '100'(用两种方式)
lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
lis[0][1][2]["k1"][1]="100"
print(lis)

lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
lis[0][1][2].update({"k1":["tt","100","1"]})
print(lis)
# 将列表li = ["alex", "seven"]转换成字典且字典的key按照10开始向后递增
li = ["alex", "seven"]
li_dic={}
for k,v in enumerate(li,10):
    li_dic[k]=v
print(li_dic)
# 有如下值集合[11,22,33,44,55,66,77,88,99,90],将所有大于66的值保存至字典的第一个key中,将小于66的值保存至第二个key的值中。
# 即:{'k1':大于66的所有值, 'k2':小于66的所有值}
li=[11,22,33,44,55,66,77,88,99,90]
li1=[]
li2=[]
for i in li:
    if i>66:
        li1.append(i)
    if i<66:
        li2.append(i)
    else:
        pass
dic = {"k1":li1,"k2":li2}
print(dic)

 

# 输出商品列表,用户输入序号,显示用户选中的商品
# 商品 li = ["手机", "电脑", '鼠标垫', '游艇']
# 允许用户添加商品
# 用户输入序号显示内
li = ["手机", "电脑", '鼠标垫', '游艇']
while True:
    print("商品信息如下".center(28,"-"))
    for index,goods in enumerate(li,1):
        print("%s %s"%(index,goods))
    choice=input("是否要添加商品(yes/no):")
    if choice == "yes" or choice=="y":
        add_goods=input("请输入要添加的商品:")
        li.append(add_goods)
    if choice == "no" or choice == "n":
        break
    else:
        print("你的输入有误,请重新输入:")
        continue

while True:
    choice_goods=input("请输入需要查询的序号,如果是非数字将会不执行")
    if choice_goods.isdigit():
        choice_goods=int(choice_goods)
        if choice_goods>=1 and choice_goods<=len(li):
            print(li[choice_goods-1])
        else:
            print("输入的序号不在范围内")
    else:
        break
# 有两个列表
# l1 = [11,22,33]
# l2 = [22,33,44]
# 获取内容相同的元素列表
l1 = [11,22,33]
l2 = [22,33,44]

s1=set(l1)
s2=set(l2)
s3=s1&s2

s3=list(s3)
print(s3)
# 获取l1和l2中内容都不同的元素

l1 = [11, 22, 33]
l2 = [22, 33, 44]

s1 = set(l1)
s2 = set(l2)
s3 = s2 ^ s1

l3 = list(s3)

print(l3)
# 利用For循环和range输出
# For循环从小到大输出1 - 100
for i in range(1,101):
    print(i)
# For循环从大到小输出100 - 1
for i in range(100,0,-1):
    print(i)
# While循环从小到大输出1 - 100
n = 1
while n <= 100:
    print(n)
    n += 1
# 利用for循环和range输出9 * 9
# 乘法表

for i in range(1, 10):
    for j in range(1, i + 1):
        print("%d*%d=%2d" % (j, i, i * j), end=" ")  # 每次输出不换行(默认print会换行),第二位数字是固定的,所以最外层循环的i代表第二位
    print(" ")  # 当j(第一位数字)遍历一遍时换行
# 判断一个数是否为素数
while True:
    flag=True
    num = input("请输入要查询的数字:")
    num = int(num)
    if num <2 :
        flag=False
    else:
        for i in (2,num):
            if i % num ==0:
                flag=False
                break
    if flag == True:
        print("%d是素数" %num)
    else:
        print("%d不是素数" %num)
# 输出100以内的所有素数
li = []
for n in range(2,101):
    flag = True
    for i in range(2,n):
        if n % i ==0:
            flag = False
            break
    if flag == True:
        li.append(n)
print(li)
# 求100以内的素数和
s = 0
for n in range(2,101):
    flag = True
    for i in range(2,n):
        if n % i == 0:
            flag = False
            break
    if flag == True:
        s += n
print(s)
# 将[1,3,2,7,6,23,41,24,33,85,56]从小到大排序(冒泡法)
li = [1,3,2,7,6,23,41,24,33,85,56]
for i in range(len(li)-1):
    if  li[i]>li[i+1]:
        li[i],li[i+1]=li[i+1],li[i]
print(li)

 

# 需求:
# 可依次选择进入各子菜单
# 可从任意一层往回退到上一层
# 可从任意一层退出程序
China = {
    '河南省': {
        '焦作市': ['武陟', '温县', '博爱'],
        '郑州市': ['新郑', '荥阳', '中牟'],
        '开封市': ['兰考', '尉氏', '杞县'],
    },
    '广东省': {
        '广州市': ['越秀', '荔湾', '番禺'],
        '深圳市': ['福田', '罗湖', '龙岗'],
        '东莞市': ['莞城', '南城', '东城'],
    },
}

exit_flag = False
while not exit_flag:
    print("     \33[31;1m欢迎来到中国\33[1m   ")
    print("\33[31;1m-----------\33[1m")
    for provinece in China:
        print(provinece)
    choice_province=input("请输入要进入的省份 输入q退出程序 输入b返回上一级")
    if choice_province == "q":
        exit_flag=True
    if choice_province == "b":
        continue
    elif choice_province in China:
        while not exit_flag:
            for city in choice_province:
                print(city)
            choice_city=input("请输入要进入的市区 输入q退出程序 输入b返回上一级")
            if choice_city == "q":
                exit_flag = True
            if choice_city == "b":
                continue
            elif choice_city in China[choice_province]:
                while not exit_flag:
                    for country in choice_city:
                        print(country)
                    choice_country = input("请输入要进入的县区 输入q退出程序 输入b返回上一级")
                    if choice_country == "q":
                        exit_flag = True
                    if choice_country == "b":
                        continue
                    elif choice_country in China[choice_province][choice_city]:
                        print("你当前的位置是%s%s%s" %(choice_province,choice_city,choice_country))
                        exit_flag = True  #得到结果后记得退出
                    else:
                        print("您输入的县区有误,请重新输入")
                        continue
            else:
                print("您的输入的市区有误,请重新输入")
                continue
    else:
        print("您的输入的省份有误,请重新输入")
        continue

 

# 购物车程序
# 功能要求:
# 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表
# 2、允许用户根据商品编号购买商品
# 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
# 4、可随时退出,退出时,打印已购买商品和余额
# 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
# 扩展需求:
# 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
# 2、允许查询之前的消费记录
# 1.0版本
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]

shopping_cars=[]
money=0
money += int(input("请输入你的工资"))
exit_flag = False
while not exit_flag:
    print("\n---------商品信息---------\n")
    for index,product in enumerate(goods,1):
        print("%s %s %s" %(index,product["name"],product["price"]))
    print("\n--------------------------\n")
    choice_product = input("请输入要购买的商品序号,输入q则退出:")
    if choice_product.isdigit():
        choice_product=int(choice_product)
        if choice_product>=1 and choice_product <= len(goods):
            if money>=goods[choice_product-1]["price"]:
                money -= goods[choice_product-1]["price"]
                shopping_cars.append(choice_product)
                print("\n\33[31;1m%s已加入购物车!\33[1m\n" %goods[choice_product-1]["name"])
            else:
                print("\n\33[31;1m加入购物车失败,工资余额已不足!\33[1m\n" )
        else:
            print("你输入的商品序号有错,请再试一次!")
    elif choice_product == "q":
        if len(shopping_cars)>0:
            print("\n\33[31;1m您当前购物车里的商品有:\33[1m\n")
            for index,product_cars in enumerate(shopping_cars,1):
                print("%s %s" %(index,product_cars))
        else:
            print("您的购物车为空")
        print("\n\33[31;1m您的工资余额为:%s 元\33[1m\n" %money)
        exit_flag = True
    else:
        pass
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import time


def select_user_info():
    # 读取用户信息文件,取出用户名、密码、锁定状态、余额组成一个用户信息字典user_info_dict
    with open(user_info_f_name, 'r', encoding='utf-8') as user_info_f:
        for line in user_info_f:  # 用户信息字符串
            user_info_list = line.strip().split(':')  # 将字符串转换为列表
            # print(user_info_list) # 用户信息列表
            _username = user_info_list[0].strip()  # 用户名
            _password = user_info_list[1].strip()  # 密码
            _lock = int(user_info_list[2].strip())  # 锁定状态,int类型(0代表未锁定,1代表锁定)
            _money = user_info_list[3].strip()  # 余额
            user_info_dict[_username] = {'password': _password, 'lock': _lock, 'money': _money}  # 将列表转换为字典
            # print(user_info_dict) # 用户信息字典


def update_user_info():
    # 修改用户信息后,更新user_info.txt文件内容
    with open(user_info_f_temp_name, "w", encoding="utf-8") as user_info_f_temp:
        for user in user_info_dict:  # 将字典转换为列表
            user_info_list_new = [user, str(user_info_dict[user]['password']), str(user_info_dict[user]['lock']),
                                  str(user_info_dict[user]['money'])]
            # print(user_info_list_new) # 更新后的用户信息列表
            user_info_str = ":".join(user_info_list_new)  # 将列表转换为字符串
            # print(user_str) # 更新后的用户信息字符串
            user_info_f_temp.write(user_info_str + "\n")
    os.replace(user_info_f_temp_name, user_info_f_name)


def product_list():
    # 商品列表
    print("\n------------商品列表------------\n")  # 商品列表
    for index, product in enumerate(goods, 1):
        print("%s.%s %d" % (index, product['name'], product['price']))
    print("\n-------------------------------")


def select_shopping_history():
    # 读取消费记录
    with open(shopping_history_f_name, "r", encoding="utf-8") as shopping_history_f:
        print("\n------------消费记录-----------\n")
        for line in shopping_history_f:
            shopping_history_list = line.strip().split('|')
            # print(shopping_history_list)
            _username = shopping_history_list[0].strip()
            _time = shopping_history_list[1].strip()
            _product = shopping_history_list[2].strip()
            if username in shopping_history_list:
                print("用户 {0} {1} 购买了 {2}".format(_username, _time, _product))
            else:
                pass
        print("\n-------------------------------")


def update_shopping_history():
    # 更新消费记录
    now_time = time.strftime('%Y-%m-%d %H:%M:%S')
    with open(shopping_history_f_name, "a", encoding="utf-8") as shopping_history_f:
        shopping_history_f.write("\n%s|%s|%s" % (username, now_time, goods[product_id - 1]['name']))


# 商品信息
goods = [
    {"name": "电脑", "price": 4000},
    {"name": "鼠标", "price": 200},
    {"name": "游艇", "price": 20000},
    {"name": "美女", "price": 1000},
    {"name": "T恤", "price": 50},
]

# 菜单栏
choice_info = """
【商品编号】购买商品
【h】消费记录
【m】余额查询
【q】退出商城

-------------------------------
"""

shopping_carts = []  # 初始购物车为空
user_info_dict = {}  # 初始化用户信息字典为空
user_info_f_name = "user_info.txt"  # 用户信息文件名
user_info_f_temp_name = "user_info.txt.temp"  # 用户信息临时文件名
shopping_history_f_name = "shopping_history.txt"  # 消费记录
exit_flag = False
count = 0

# 主程序开始
select_user_info()  # 读取用户信息文件,组成user_info_dict字典
while count < 3 and not exit_flag:
    username = input('\n请输入用户名:')
    if username not in user_info_dict:
        count += 1
        print("\n用户名错误")
    elif user_info_dict[username]['lock'] > 0:
        print("\n用户已被锁定,请联系管理员解锁后重新尝试")
        break
    else:
        while count < 3 and not exit_flag:
            password = input('\n请输入密码:')
            if password == user_info_dict[username]['password']:
                print("\n--------欢迎%s登陆本商城--------" % (username))
                if int(user_info_dict[username]['money']) == 0:  # money = 0表示是首次登陆的用户
                    while True:
                        money = input("\n请输入您的工资:")  # 工资只能是数字
                        if money.isdigit():
                            money = int(money)
                            # print(money)
                            break
                        else:
                            print("\n您的工资只能是数字")
                            continue
                else:
                    money = int(user_info_dict[username]['money'])
                    print("\n\33[31;1m您上次购物后的余额为:%s 元!\33[1m\n" % (money))
                while not exit_flag:
                    product_list()  # 打印商品列表
                    print(choice_info)  # 选择信息
                    product_id = input("请输入您要的操作:")
                    if product_id.isdigit():
                        product_id = int(product_id)
                        if product_id >= 1 and product_id <= len(goods):
                            if money >= goods[product_id - 1]['price']:
                                money -= goods[product_id - 1]['price']
                                shopping_carts.append(goods[product_id - 1]['name'])
                                print("\n\33[31;1m%s已购买成功!\33[1m\n" % (goods[product_id - 1]['name']))
                                update_shopping_history()  # 写入消费记录文件
                                user_info_dict[username]['money'] = money
                                update_user_info()  # 更新工资余额到文件
                            else:
                                print(
                                    "\n\33[31;1m抱歉,%s购买失败!工资余额不足!\33[1m\n" % (goods[product_id - 1]['name']))
                        else:
                            print("商品标号有误,请重新输入")
                    elif product_id == "q":
                        if len(shopping_carts) > 0:
                            print("\n\33[31;1m您本次购买的商品及商品数量如下:\33[1m\n")
                            shopping_carts_delRepeat = list(set(shopping_carts))  # 购物车列表去重
                            for index, product_carts in enumerate(shopping_carts_delRepeat, 1):
                                print("%s. %s * %d" % (
                                    index, product_carts, shopping_carts.count(product_carts)))  # 显示同一商品数量
                        else:
                            print("\n您本次没有购买东西!")
                        print("\n\33[31;1m您的工资余额为:%s 元!\33[1m\n" % (money))
                        # user_info_dict[username]['money'] = money
                        # update_user_info()  # 更新工资余额到文件
                        exit_flag = True
                    elif product_id == "h":
                        select_shopping_history()
                        choice_continue = input("\n回到菜单栏(直接按回车):")
                        if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "":
                            continue
                        else:
                            print("\n操作失误,强制退出!")
                            exit_flag = True
                    elif product_id == "m":
                        print("\n\33[31;1m您的工资余额为:%s 元!\33[1m\n" % (money))
                        # user_info_dict[username]['money'] = money
                        # update_user_info()  # 更新工资余额到文件
                        choice_continue = input("\n回到菜单栏(直接按回车):")
                        if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "":
                            continue
                        else:
                            print("\n操作失误,强制退出!")
                            exit_flag = True
                    else:
                        print("\n输入有误,请重新输入")
            else:
                count += 1
                print('\n密码错误')
                continue
    if count >= 3:  # 尝试次数大于等于3时锁定用户
        if username == "":
            print("\n您输入的错误次数过多,且用户为空")
        elif username not in user_info_dict:
            print("\n您输入的错误次数过多,且用户 %s 不存在" % username)
        else:
            user_info_dict[username]['lock'] += 1  # 修改用户字典(锁定状态设为1)
            # print(user_info_dict) # 更新后的用户信息字典
            update_user_info()  # 更新user_info.txt文件内容
            print("\n您输入的错误次数过多,%s 已经被锁定" % username)
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import time


def select_user_info():
    # 读取用户信息文件,取出用户名、密码、锁定状态、余额组成一个用户信息字典user_info_dict
    with open(user_info_f_name, 'r', encoding='utf-8') as user_info_f:
        for line in user_info_f:  # 用户信息字符串
            user_info_list = line.strip().split(':')  # 将字符串转换为列表
            # print(user_info_list) # 用户信息列表
            _username = user_info_list[0].strip()  # 用户名
            _password = user_info_list[1].strip()  # 密码
            _lock = int(user_info_list[2].strip())  # 锁定状态,int类型(0代表未锁定,1代表锁定)
            _money = user_info_list[3].strip()  # 余额
            user_info_dict[_username] = {'password': _password, 'lock': _lock, 'money': _money}  # 将列表转换为字典
            # print(user_info_dict) # 用户信息字典


def update_user_info():
    # 修改用户信息后,更新user_info.txt文件内容
    with open(user_info_f_temp_name, "w", encoding="utf-8") as user_info_f_temp:
        for user in user_info_dict:  # 将字典转换为列表
            user_info_list_new = [user, str(user_info_dict[user]['password']), str(user_info_dict[user]['lock']),
                                  str(user_info_dict[user]['money'])]
            # print(user_info_list_new) # 更新后的用户信息列表
            user_info_str = ":".join(user_info_list_new)  # 将列表转换为字符串
            # print(user_str) # 更新后的用户信息字符串
            user_info_f_temp.write(user_info_str + "\n")
    os.replace(user_info_f_temp_name, user_info_f_name)


def product_list():
    # 商品列表
    print("\n------------商品列表------------\n")  # 商品列表
    for index, product in enumerate(goods, 1):
        print("%s.%s %d" % (index, product['name'], product['price']))
    print("\n-------------------------------")


def select_shopping_history():
    # 读取消费记录
    with open(shopping_history_f_name, "r", encoding="utf-8") as shopping_history_f:
        print("\n---------您的消费记录----------\n")
        for line in shopping_history_f:
            shopping_history_list = line.strip().split('|')
            # print(shopping_history_list)
            _username = shopping_history_list[0].strip()
            _time = shopping_history_list[1].strip()
            _product = shopping_history_list[2].strip()
            if username in shopping_history_list:
                print("用户 {0} {1} 购买了 {2}".format(_username, _time, _product))
            else:
                pass
        print("\n-------------------------------")


def update_shopping_history():
    # 更新消费记录
    now_time = time.strftime('%Y-%m-%d %H:%M:%S')
    with open(shopping_history_f_name, "a", encoding="utf-8") as shopping_history_f:
        shopping_history_f.write("\n%s|%s|%s" % (username, now_time, goods[product_id - 1]['name']))


# 商品信息
goods = [
    {"name": "电脑", "price": 4000},
    {"name": "鼠标", "price": 200},
    {"name": "游艇", "price": 20000},
    {"name": "美女", "price": 1000},
    {"name": "T恤", "price": 50},
]

# 菜单栏
choice_info = """
【商品编号】购买商品
【h】消费记录
【m】余额查询
【q】退出商城

-------------------------------
"""

shopping_carts = []  # 初始购物车为空
user_info_dict = {}  # 初始化用户信息字典为空
user_info_f_name = "user_info.txt"  # 用户信息文件名
user_info_f_temp_name = "user_info.txt.temp"  # 用户信息临时文件名
shopping_history_f_name = "shopping_history.txt"  # 消费记录
exit_flag = False
count = 0

# 主程序开始
select_user_info()  # 读取用户信息文件,组成user_info_dict字典
while count < 3 and not exit_flag:
    username = input('\n请输入用户名:')
    if username not in user_info_dict:
        count += 1
        print("\n用户名错误")
    elif user_info_dict[username]['lock'] > 0:
        print("\n用户已被锁定,请联系管理员解锁后重新尝试")
        break
    else:
        while count < 3 and not exit_flag:
            password = input('\n请输入密码:')
            if password == user_info_dict[username]['password']:
                print("\n--------欢迎%s登陆本商城--------" % (username))
                if int(user_info_dict[username]['money']) == 0:  # money = 0表示是首次登陆的用户
                    while True:
                        money = input("\n请输入您的工资:")  # 工资只能是数字
                        if money.isdigit():
                            money = int(money)
                            # print(money)
                            break
                        else:
                            print("\n您的工资只能是数字")
                            continue
                else:
                    money = int(user_info_dict[username]['money'])
                    print("\n\033[31;1m您上次购物后的余额为:%s 元!\033[0m\n" % (money))
                while not exit_flag:
                    product_list()  # 打印商品列表
                    print(choice_info)  # 选择信息
                    product_id = input("请输入您要的操作:")
                    if product_id.isdigit():
                        product_id = int(product_id)
                        if product_id >= 1 and product_id <= len(goods):
                            if money >= goods[product_id - 1]['price']:
                                money -= goods[product_id - 1]['price']
                                shopping_carts.append(goods[product_id - 1]['name'])
                                print("\n\033[31;1m%s已购买成功!\033[0m\n" % (goods[product_id - 1]['name']))
                                update_shopping_history()  # 写入消费记录文件
                                user_info_dict[username]['money'] = money
                                update_user_info()  # 更新工资余额到文件
                            else:
                                print("\n\033[31;1m抱歉,%s购买失败!工资余额不足!\033[0m" % (goods[product_id - 1]['name']))
                        else:
                            print("商品标号有误,请重新输入")
                    elif product_id == "q":
                        if len(shopping_carts) > 0:
                            print("\n\033[31;1m您本次购买的商品及商品数量如下:\033[0m\n")
                            shopping_carts_delRepeat = list(set(shopping_carts))  # 购物车列表去重
                            for index, product_carts in enumerate(shopping_carts_delRepeat, 1):
                                print("%s. %s * %d" % (
                                    index, product_carts, shopping_carts.count(product_carts)))  # 显示同一商品数量
                        else:
                            print("\n您本次没有购买东西!")
                        print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money))
                        # user_info_dict[username]['money'] = money
                        # update_user_info()  # 更新工资余额到文件
                        exit_flag = True
                    elif product_id == "h":
                        select_shopping_history()
                        choice_continue = input("\n回到菜单栏(直接按回车):")
                        if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "":
                            continue
                        else:
                            print("\n操作失误,强制退出!")
                            exit_flag = True
                    elif product_id == "m":
                        print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money))
                        # user_info_dict[username]['money'] = money
                        # update_user_info()  # 更新工资余额到文件
                        choice_continue = input("\n回到菜单栏(直接按回车):")
                        if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "":
                            continue
                        else:
                            print("\n操作失误,强制退出!")
                            exit_flag = True
                    else:
                        print("\n输入有误,请重新输入")
            else:
                count += 1
                print('\n密码错误')
                continue
    if count >= 3:  # 尝试次数大于等于3时锁定用户
        if username == "":
            print("\n您输入的错误次数过多,且用户为空")
        elif username not in user_info_dict:
            print("\n您输入的错误次数过多,且用户 %s 不存在" % username)
        else:
            user_info_dict[username]['lock'] += 1  # 修改用户字典(锁定状态设为1)
            # print(user_info_dict) # 更新后的用户信息字典
            update_user_info()  # 更新user_info.txt文件内容
            print("\n您输入的错误次数过多,%s 已经被锁定" % username)

 

---恢复内容结束---

推荐阅读