前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >80-综合练习:记账小程序

80-综合练习:记账小程序

作者头像
凯茜的老爸
发布2018-09-11 15:00:45
4860
发布2018-09-11 15:00:45
举报
文章被收录于专栏:python百例python百例

1、记账时手头有一万块钱 2、可以记录花的钱、存的钱,以及收支明细

代码语言:javascript
复制
import pickle
import os
import time


def cost(wallet, record):  # 记录花钱的函数
    amount = int(input('amount: '))
    comment = input('comment: ')
    date = time.strftime('%Y-%m-%d')
    with open(wallet, 'rb') as fobj:
        balance = pickle.load(fobj) - amount
    with open(wallet, 'wb') as fobj:
        pickle.dump(balance, fobj)
    with open(record, 'a') as fobj:
        fobj.write(
            '%-12s%-8s%-8s%-10s%-20s\n' % (date, amount, '', balance, comment)
        )

def save(wallet, record):  # 记录存钱的函数
    amount = int(input('amount: '))
    comment = input('comment: ')
    date = time.strftime('%Y-%m-%d')
    with open(wallet, 'rb') as fobj:
        balance = pickle.load(fobj) + amount
    with open(wallet, 'wb') as fobj:
        pickle.dump(balance, fobj)
    with open(record, 'a') as fobj:
        fobj.write(
            '%-12s%-8s%-8s%-10s%-20s\n' % (date, '', amount, balance, comment)
        )

def query(wallet, record):  # 查询收支明细的函数
    print('%-12s%-8s%-8s%-10s%-20s' % ('date', 'cost', 'save', 'balace', 'comment'))
    with open(record) as fobj:
        for line in fobj:
            print(line, end='')
    with open(wallet, 'rb') as fobj:
        balance = pickle.load(fobj)
    print("Latest Balance: %d" % balance)


def show_menu():
    cmds = {'0': cost, '1': save, '2': query}
    prompt = """(0) cost
(1) save
(2) query
(3) exit
Please input your choice(0/1/2/3): """
    wallet = 'wallet.data'
    record = 'record.txt'
    if not os.path.exists(wallet):
        with open(wallet, 'wb') as fobj:
            pickle.dump(10000, fobj)

    while True:
        try:
            choice = input(prompt).strip()[0]
        except IndexError:
            continue
        except (KeyboardInterrupt, EOFError):
            print()
            choice = '3'

        if choice not in '0123':
            print('Invalid input. Try again.')
            continue

        if choice == '3':
            break
        cmds[choice](wallet, record)

if __name__ == '__main__':
    show_menu()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.08.02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档