while True: user_id = input("请输入学号:") password = input("请输入密码:") # 验证学号和密码是否正确 if user_id in users.keys() and password == users[user_id]: print("登录成功!") break else: error_count += 1 if error_count == 3: # 密码错误达到三次,冻结账号 print("密码错误次数达到三次,账号已被冻结!") break else: print("学号或密码错误,请重新输入!") 改成for循环
时间: 2024-02-10 14:21:27 浏览: 96
可以将上述代码改写成 for 循环,如下所示:
for i in range(3): # 最多允许输入三次
user_id = input("请输入学号:")
password = input("请输入密码:")
# 验证学号和密码是否正确
if user_id in users.keys() and password == users[user_id]:
print("登录成功!")
break
else:
if i == 2: # 输入三次后仍然错误,冻结账号
print("密码错误次数达到三次,账号已被冻结!")
break
else:
print("学号或密码错误,请重新输入!")
相关问题
使用 mysql 保存数据,实现超市日常管理中以下业务。" 一、建立以下数据表并填充数据+登录+' 用户表: users _学号后四位+' 列名: id _学号后四位用户名 name 学号后四位密码: pwd _学号后四位*产品表: products _学号后四位. 列名: id _学号后四位编号 num 学号后四位名称 name 学号后四位单价 price 学号后四位折扣 discount _学号后四位 订单表: orders _学号后四位. 列名: id _学号后四位编号 num 学号后四位货品数量 count 学号后四位金额 arnount 学号后四位. 二、实现以下菜单并实现业务0用户登录 1查看所有产品信息。"2查找商品(用户输入商品名称,查看价格和折扣):- 3添加商品(需要程序生成编号),- 4修改商品价格和折扣(折扣为0.1-0.99之间):. 5删除商品(根据编号): 6查看所有订单:+ 7.订单统计(显示总销售额和货品数量): 8.商品结算。,每个声明的变量加上_0314结尾,并且所有自定义的变量加上_0314,例如a_0314=1
好的,下面是使用 Python 和 MySQL 实现超市日常管理的代码:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='123456', database='supermarket')
cur = conn.cursor()
# 用户登录
def login():
username = input("请输入用户名:")
pwd = input("请输入密码:")
sql = "SELECT * FROM users WHERE name=%s AND pwd=%s"
cur.execute(sql, (username, pwd))
result = cur.fetchone()
if result:
print("登录成功!")
else:
print("用户名或密码错误!")
# 查看所有产品信息
def view_products():
sql = "SELECT * FROM products"
cur.execute(sql)
result = cur.fetchall()
for row in result:
print(row)
# 查找商品
def search_product():
product_name = input("请输入商品名称:")
sql = "SELECT price, discount FROM products WHERE name=%s"
cur.execute(sql, product_name)
result = cur.fetchone()
if result:
print("价格:", result[0], "折扣:", result[1])
else:
print("没有找到该商品!")
# 添加商品
def add_product():
product_name = input("请输入商品名称:")
price_0314 = input("请输入单价:")
discount_0314 = input("请输入折扣:")
num_0314 = 'p' + str(len(product_name)) + product_name[-4:] # 自动生成编号
sql = "INSERT INTO products (id, num, name, price, discount) VALUES (%s, %s, %s, %s, %s)"
cur.execute(sql, (num_0314, num_0314, product_name, price_0314, discount_0314))
conn.commit()
print("添加成功!")
# 修改商品价格和折扣
def modify_product():
num_0314 = input("请输入要修改的商品编号:")
price_0314 = input("请输入新的单价:")
discount_0314 = input("请输入新的折扣:")
sql = "UPDATE products SET price=%s, discount=%s WHERE num=%s"
cur.execute(sql, (price_0314, discount_0314, num_0314))
conn.commit()
print("修改成功!")
# 删除商品
def delete_product():
num_0314 = input("请输入要删除的商品编号:")
sql = "DELETE FROM products WHERE num=%s"
cur.execute(sql, num_0314)
conn.commit()
print("删除成功!")
# 查看所有订单
def view_orders():
sql = "SELECT * FROM orders"
cur.execute(sql)
result = cur.fetchall()
for row in result:
print(row)
# 订单统计
def order_statistics():
sql = "SELECT SUM(count), SUM(amount) FROM orders"
cur.execute(sql)
result = cur.fetchone()
print("总销售额:", result[1], "货品数量:", result[0])
# 商品结算
def checkout():
total_amount = 0
while True:
product_num = input("请输入商品编号(输入0结束结算):")
if product_num == '0':
break
count_0314 = int(input("请输入货品数量:"))
sql = "SELECT price, discount FROM products WHERE num=%s"
cur.execute(sql, product_num)
result = cur.fetchone()
if result:
price_0314, discount_0314 = result
amount_0314 = price_0314 * discount_0314 * count_0314
total_amount += amount_0314
sql = "INSERT INTO orders (id, num, count, amount) VALUES (%s, %s, %s, %s)"
cur.execute(sql, ('o' + str(len(str(total_amount))) + str(total_amount)[-4:], product_num, count_0314, amount_0314))
conn.commit()
else:
print("没有找到该商品!")
print("总金额为:", total_amount)
# 菜单
while True:
print("=====超市日常管理系统=====")
print("0. 用户登录")
print("1. 查看所有产品信息")
print("2. 查找商品")
print("3. 添加商品")
print("4. 修改商品价格和折扣")
print("5. 删除商品")
print("6. 查看所有订单")
print("7. 订单统计")
print("8. 商品结算")
print("==========================")
choice_0314 = input("请输入您要进行的操作:")
if choice_0314 == '0':
login()
elif choice_0314 == '1':
view_products()
elif choice_0314 == '2':
search_product()
elif choice_0314 == '3':
add_product()
elif choice_0314 == '4':
modify_product()
elif choice_0314 == '5':
delete_product()
elif choice_0314 == '6':
view_orders()
elif choice_0314 == '7':
order_statistics()
elif choice_0314 == '8':
checkout()
else:
print("输入有误,请重新输入!")
# 关闭连接
cur.close()
conn.close()
```
注意事项:
1. 需要先创建数据库和数据表,并填充数据,详情请见下面的 SQL 语句。
2. 在 MySQL 中,表名不区分大小写,但列名区分大小写,因此在编写 SQL 语句时需要注意。
3. 为每个变量加上 _0314 后缀是为了避免与 Python 内置函数或关键字重名。
下面是创建数据库和数据表的 SQL 语句:
```sql
-- 创建数据库
CREATE DATABASE supermarket;
-- 创建用户表
CREATE TABLE users (
id VARCHAR(10) NOT NULL,
name VARCHAR(10) NOT NULL,
pwd VARCHAR(10) NOT NULL,
PRIMARY KEY (id)
);
-- 插入用户数据
INSERT INTO users (id, name, pwd) VALUES ('u0314', '0314', '0314');
-- 创建产品表
CREATE TABLE products (
id VARCHAR(10) NOT NULL,
num VARCHAR(10) NOT NULL,
name VARCHAR(20) NOT NULL,
price FLOAT NOT NULL,
discount FLOAT NOT NULL,
PRIMARY KEY (id)
);
-- 插入产品数据
INSERT INTO products (id, num, name, price, discount) VALUES ('p5milk', 'p5milk', '牛奶', 2.5, 0.9);
INSERT INTO products (id, num, name, price, discount) VALUES ('p6bread', 'p6bread', '面包', 1.5, 0.8);
INSERT INTO products (id, num, name, price, discount) VALUES ('p8apple', 'p8apple', '苹果', 5, 0.95);
-- 创建订单表
CREATE TABLE orders (
id VARCHAR(10) NOT NULL,
num VARCHAR(10) NOT NULL,
count INT NOT NULL,
amount FLOAT NOT NULL,
PRIMARY KEY (id)
);
```
在运行代码前,需要先在 MySQL 中创建数据库和数据表,并填充数据。
三个表:用户表user和管理员表admin和图书表book 用户表user(用户名uname,密码password,姓名chrname,角色role) 图书表books(图书编号bid,图书名bname,作者aut) 图书借阅(用户名uname,图书编号bid,图书名bname,作者aut,时间date) 在user.txt中存放可以登录的用户信息(用户名,密码,姓名) book.txt以txt格式存放图书信息 运行程序时,首先输入用户名和密码,不正确提示用户重新输入,最多可以尝试3次,用户名密码正确后进入主菜单,如下所示: ====图书借阅管理系统==== 1.txt文件读取图书信息 2.键盘添加图书信息.(仅限2.3.4管理员功能) 3.修改某条图书信息 4.删除某条图书信息 5.增加一条用户借书记录 (5.6.7.8.9用户功能) 6.删除一条用户借书记录(还书) 7.通过学号修改用户的某条借书记录 8.通过学号查找用户借书还书记录 9.控制台直接显示用户借书记录 10.修改登录密码 11.txt导出图书信息 12.退出 请选择(1-12):
这是一道比较典型的数据库应用题目,需要使用文件读写和基本的数据操作知识。下面是一个简单的实现思路:
1. 读取user.txt文件中的用户信息,存储到一个字典中,用于登录验证和修改密码。
2. 读取book.txt文件中的图书信息,存储到一个列表中。
3. 实现登录验证功能,最多可以尝试3次,如果用户名或密码不正确则提示用户重新输入。
4. 登录成功后显示主菜单,根据用户的角色(role)显示不同的选项。
5. 如果用户角色是管理员,则可以进行图书信息的添加、修改和删除操作。如果是普通用户,则只能进行借书和还书操作。
6. 图书信息的添加、修改和删除操作需要对book.txt文件进行读写。可以使用csv模块来实现,也可以使用普通的文本文件读写。
7. 借书和还书操作需要对一个借阅记录文件进行读写,可以使用csv模块来实现。借阅记录文件的格式为:用户名,图书编号,图书名,作者,借阅时间。
8. 修改密码功能需要对user.txt文件进行读写。
9. 导出图书信息功能需要将book.txt文件的内容输出到一个新的文件中,可以使用csv模块来实现。
10. 程序退出前需要保存所有的数据到相应的文件中。
下面是一个简单的Python代码示例,仅供参考:
```python
import csv
def read_users(filename):
users = {}
with open(filename, 'r') as f:
reader = csv.reader(f)
for row in reader:
username, password, name, role = row
users[username] = {'password': password, 'name': name, 'role': role}
return users
def write_users(filename, users):
with open(filename, 'w') as f:
writer = csv.writer(f)
for username, info in users.items():
password = info['password']
name = info['name']
role = info['role']
writer.writerow([username, password, name, role])
def read_books(filename):
books = []
with open(filename, 'r') as f:
reader = csv.reader(f)
for row in reader:
bid, bname, author = row
books.append({'bid': bid, 'bname': bname, 'author': author})
return books
def write_books(filename, books):
with open(filename, 'w') as f:
writer = csv.writer(f)
for book in books:
bid = book['bid']
bname = book['bname']
author = book['author']
writer.writerow([bid, bname, author])
def read_records(filename):
records = []
with open(filename, 'r') as f:
reader = csv.reader(f)
for row in reader:
username, bid, bname, author, date = row
records.append({'username': username, 'bid': bid, 'bname': bname, 'author': author, 'date': date})
return records
def write_records(filename, records):
with open(filename, 'w') as f:
writer = csv.writer(f)
for record in records:
username = record['username']
bid = record['bid']
bname = record['bname']
author = record['author']
date = record['date']
writer.writerow([username, bid, bname, author, date])
def login(users):
for i in range(3):
username = input('请输入用户名:')
password = input('请输入密码:')
if username in users and users[username]['password'] == password:
print('登录成功!')
return username, users[username]['role']
else:
print('用户名或密码不正确,请重新输入。')
print('登录失败!')
return None, None
def add_book(books):
bid = input('请输入图书编号:')
bname = input('请输入图书名称:')
author = input('请输入作者名称:')
books.append({'bid': bid, 'bname': bname, 'author': author})
print('添加图书成功!')
def modify_book(books):
bid = input('请输入要修改的图书编号:')
for book in books:
if book['bid'] == bid:
book['bname'] = input('请输入新的图书名称:')
book['author'] = input('请输入新的作者名称:')
print('修改图书成功!')
return
print('没有找到该图书编号!')
def delete_book(books):
bid = input('请输入要删除的图书编号:')
for book in books:
if book['bid'] == bid:
books.remove(book)
print('删除图书成功!')
return
print('没有找到该图书编号!')
def borrow_book(username, books, records):
bid = input('请输入要借阅的图书编号:')
for book in books:
if book['bid'] == bid:
bname = book['bname']
author = book['author']
records.append({'username': username, 'bid': bid, 'bname': bname, 'author': author, 'date': '借阅时间'})
print('借阅图书成功!')
return
print('没有找到该图书编号!')
def return_book(username, records):
bid = input('请输入要归还的图书编号:')
for record in records:
if record['username'] == username and record['bid'] == bid:
record['date'] = '归还时间'
print('归还图书成功!')
return
print('没有找到该图书编号或您没有借阅过该图书!')
def modify_record(username, records):
bid = input('请输入要修改的图书编号:')
for record in records:
if record['username'] == username and record['bid'] == bid:
record['date'] = input('请输入新的借阅时间或归还时间:')
print('修改借阅记录成功!')
return
print('没有找到该图书编号或您没有借阅过该图书!')
def search_record(username, records):
for record in records:
if record['username'] == username:
print(record)
def main():
users = read_users('user.txt')
books = read_books('book.txt')
records = read_records('record.csv')
username, role = login(users)
if username is None:
return
while True:
print('====图书借阅管理系统====')
print('1.读取图书信息')
if role == '管理员':
print('2.添加图书信息')
print('3.修改图书信息')
print('4.删除图书信息')
elif role == '用户':
print('5.借阅图书')
print('6.归还图书')
print('7.修改借阅记录')
print('8.查找借阅记录')
print('9.显示借阅记录')
print('10.修改登录密码')
print('11.导出图书信息')
print('12.退出')
choice = input('请选择(1-12):')
if choice == '1':
for book in books:
print(book)
elif choice == '2' and role == '管理员':
add_book(books)
elif choice == '3' and role == '管理员':
modify_book(books)
elif choice == '4' and role == '管理员':
delete_book(books)
elif choice == '5' and role == '用户':
borrow_book(username, books, records)
elif choice == '6' and role == '用户':
return_book(username, records)
elif choice == '7' and role == '用户':
modify_record(username, records)
elif choice == '8' and role == '用户':
search_record(username, records)
elif choice == '9' and role == '用户':
for record in records:
if record['username'] == username:
print(record)
elif choice == '10':
new_password = input('请输入新的密码:')
users[username]['password'] = new_password
write_users('user.txt', users)
print('修改密码成功!')
elif choice == '11':
write_books('book_out.csv', books)
print('导出图书信息成功!')
elif choice == '12':
write_users('user.txt', users)
write_books('book.txt', books)
write_records('record.csv', records)
print('程序退出!')
break
if __name__ == '__main__':
main()
```
注意:上述代码仅供参考,还有很多细节和错误处理需要完善。实际应用中,还需要考虑并发访问、数据安全、备份恢复等问题。
阅读全文