Python小例-8-记账小程序

Python020

Python小例-8-记账小程序,第1张

import pickle

import time

import os

def cost(fname):

    '用于记录花费'

    cost_time = time.strftime('%Y-%m-%d')

    try:#异常处理机制

        cost_deposit = int(input('花销金额:'))

        cost_mark = input('花销说明:')

    except ValueError:

        print('无效的金额')

        return # 函数的return类似于循环的break,return提前结束函数。

    except (KeyboardInterrupt, EOFError):

        print('\nbye-bye')

        exit(1)

    # 在文件中取出所有的收支记录

    with open(fname,'rb') as fobj:

        records = pickle.load(fobj)

    # 计算最新余额

    balance = records[-1][-2] - cost_deposit

    # 构建最新一笔收入

    record = [cost_time,0,cost_deposit,balance,cost_mark]

    # 将收入追加到收支列表中

    records.append(record)

    # 将最新收支情况写入文件

    with open(fname,'wb') as fobj:

        pickle.dump(records,fobj)

def save(fname):

    save_time = time.strftime('%Y-%m-%d')

    try:

        save_deposit = int(input('收入金额:'))

        save_mark = input('收入说明:')

    except ValueError:

        print('无效的金额')

        return

    except (KeyboardInterrupt,EOFError):

        print('bye-bye')

        exit(1)

    with open(fname, 'rb') as fobj:

        records = pickle.load(fobj)

    balance = records[-1][-2] +  save_deposit

    record = [save_time,save_deposit,0,balance, save_mark]

    records.append(record)

    with open(fname, 'wb') as fobj:

        pickle.dump(records, fobj)

def query(fname):

    '用于查账'

    # 打印表头

    print(f'{"date":<15}{"save":<8}{"cost":<8}{"balance":<12}{"mark":<50}')

    with open(fname,'rb') as fobj:

        records = pickle.load(fobj)

    for date,cost,save,balance,mark in records:

        print(f'{date:<15}{cost:<8}{save:<8}{balance:<12}{mark:<50}')

def menu():

    funcs = {'0':cost,'1':save,'2':query}

    prompt = '''(0)开销

(1)收入

(2)查询

(3)退出

请选择(0/1/2/3):'''

    fname = 'account.data'

    if not os.path.exists(fname):

        init_data = [[time.strftime('%Y-%m-%d'),0,0,10000,'init_data']]

        with open(fname,'wb') as fobj:

            pickle.dump(init_data,fobj)

    while 1:

        try:

            choice = input(prompt).strip()

        except(KeyboardInterrupt,EOFError):

            choice = '3'

        if choice not in ['0','1','2','3']:

            print('无效输入,重试')

            continue

        if choice == '3':

            print('\nbye_bye')

            break

        funcs[choice](fname)

if __name__ == '__main__':

    menu()

python在财会领域应用:可以用来处理数据,进行更深层次的数据分析,评估预算的时候,快速数据对比。

python相比php\ruby的模块化设计,非常便于功能扩展;多年来形成了大量优秀的web开发框架,并且在不断迭代;如目前优秀的全栈的django、框架flask,都继承了python简单、明确的风格,开发效率高、易维护,与自动化运维结合性好。

Python

是完全面向对象的语言。函数、模块、数字、字符串都是对象。并且完全支持继承、重载、派生、多继承,有益于增强源代码的复用性。Python支持重载运算符和动态类型。相对于Lisp这种传统的函数式编程语言,Python对函数式设计只提供了有限的支持。有两个标准库(functools, itertools)提供了Haskell和Standard ML中久经考验的函数式程序设计工具。