小项目练手
项目:个人记账小助手
目标:用函数把一个命令行小程序拆分清楚,练习“参数设计、返回值设计、数据校验和功能拆分”。
建议功能:
- 显示菜单
- 添加一条收入记录
- 添加一条支出记录
- 查看所有记录
- 按类型统计总金额
- 统计总收入、总支出、当前结余
- 按关键词查询记录
- 删除指定记录
代码
def show_menu():
print("\n===== 个人记账小助手 =====")
print("1. 添加一条记录")
print("2. 查看所有记录")
print("3. 删除一条记录")
print("4. 查找一条记录")
print("5. 按类型统计总金额")
print("0. 退出程序")
def add_record(records, kind, amount, note):
if is_valid_amount(amount):
if is_valid_kind(kind):
new_record = {'kind': kind, 'amount': amount, 'note': note}
records.append(new_record)
print("添加成功!")
return
else:
print("收支类型必须是收入或支出")
return
else:
print("金额必须大于 0")
return
def show_records(records):
length = len(records)
print("所有记录如下:")
for index in range(length):
print(index, records[index])
def delete_record(records, index):
if index < 0 or index >= len(records):
print("索引号无效")
return
else:
print("删除的记录如下:")
print(index, records[index])
records.pop(index)
def search_records(records, keyword):
found = False
print("查找结果如下:")
for index in range(len(records)):
if (keyword in records[index]['note']):
print(index, records[index])
found = True
if not found:
print("未找到相关记录")
def calc_by_kind(records, kind):
total_num1 = 0
total_num2 = 0
for index in range(len(records)):
if records[index]['kind'] == '收入':
total_num1 = total_num1 + records[index]['amount']
else:
total_num2 = total_num2 + records[index]['amount']
if kind == '收入':
print("收入总金额为:", total_num1)
elif kind == '支出':
print("支出总金额为:", total_num2)
else:
print("输入无效")
def is_valid_amount(amount):
if amount <= 0:
return False
else:
return True
def is_valid_kind(kind):
if kind == '收入' or kind == '支出':
return True
else:
return False
def main():
records = []
while True:
show_menu()
choice = input("请输入操作:").strip()
match choice:
case '0':
print("程序已退出")
break
case '1':
kind, amount, note = input("请输入类别、金额、记录:").split()
add_record(records, kind, float(amount), note)
continue
case '2':
show_records(records)
continue
case '3':
show_records(records)
index = int(input("请输入要删除记录的索引号:"))
delete_record(records, index)
continue
case '4':
keyword = input("请输入关键词:").strip()
search_records(records, keyword)
continue
case '5':
kind = input("请输入您想统计的类别:").strip()
calc_by_kind(records, kind)
continue
case _:
print("输入无效,请重新输入:")
continue
if __name__ == '__main__':
main()
浙公网安备 33010602011771号