python实现日常记账本小程序

yipeiwu_com6年前Python基础

python实现收支的自动计算,能够查询每笔账款的消费详情,具体内容如下

1、函数需要两个文件:一个类似钱包功能,存放钱;另一个用于记录每笔花销的用途

#!/usr/bin/env python 
import cPickle as p 
 
with open('wallet.data','w') as f: 
  p.dump(10000,f) 
 
with open('record.txt','w') as f: 
  pass 

2、功能实现

#!!/usr/bin/env python 
#coding:utf8 
 
import cPickle as p 
import time 
 
date = time.strftime('%Y%m%d') 
 
def save_money(): 
  sav_count=int(raw_input('save money: ')) 
  sav_comment = raw_input('doing what: ') 
 
  with open('wallet.data') as f: 
    balance = p.load(f) 
 
  new_bal = balance + sav_count 
  with open('wallet.data','w') as f: 
    p.dump(new_bal,f) 
 
  content = '%-12s%-8s%-8s%-10s%-25s\n'%(date,'N/A',sav_count,new_bal,sav_comment) 
  with open('record.txt','a')as f: 
    f.write(content) 
 
 
 
def spend_money(): 
  spe_count=int(raw_input('spend money: ')) 
  spe_comment = raw_input('doing what: ') 
 
  with open('wallet.data') as f: 
    balance = p.load(f) 
 
  new_bal = balance - spe_count 
  with open('wallet.data','w') as f: 
    p.dump(new_bal,f) 
 
  with open('record.txt','a')as f: 
    content = '%-12s%-8s%-8s%-10s%-25s\n'%(date,spe_count,'N/A',new_bal,spe_comment) 
    f.write(content) 
 
def query_info(): 
  line = '='*63 
  content = '%s\n%-12s%-8s%-8s%-10s%-25s'%(line,'Date','Cost','Save','Balance','Comment') 
 
  with open('wallet.data') as f: 
    new_bal = p.load(f) 
 
  print 'new balance: ',new_bal 
 
  print content 
  with open('record.txt') as f: 
    for line in f: 
       print line 
 
 
 
def show_menu(): 
  prompt = ''''' 
  '0':'spend_money' 
  '1':'save_money' 
  '2':'query_info' 
  '3':'quit' 
''' 
  while True: 
    CMDs={'0':spend_money,'1':save_money,'2':query_info} 
    choice = raw_input('which do you want to do ?%s: '%prompt) 
    if choice not in '012': 
      break 
    CMDs[choice]() 
 
 
if __name__=='__main__': 
  show_menu() 

3、程序还有改进处,例如将两个文件以参数的形式传入,会简化代码。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3.6实现学生信息管理系统

简单版本学生信息管理系统,用python基础语法实现,基于python 3.6 容错率很高的代码,做了很多异常处理功能,出错也不会丢失信息 启动时自动从文件中读取已有学生信息,退出时自动...

对python3中pathlib库的Path类的使用详解

对python3中pathlib库的Path类的使用详解

用了很久的os.path,今天发现竟然还有这么好用的库,记录下来以便使用。 1.调用库 from pathlib import 2.创建Path对象 p = Path('D:...

Python有参函数使用代码实例

这篇文章主要介绍了Python有参函数使用代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.给定验证码长度n,生成随机验证码...

pyinstaller打包多个py文件和去除cmd黑框的方法

pyinstaller打包多个py文件和去除cmd黑框的方法

1.打包多个py文件并且去除cmd黑框 格式:pyinstaller.exe -F 路径\文件名.py空格路径\文件名.py空格--noconsole 以上这篇pyinstaller打...

在Pycharm中对代码进行注释和缩进的方法详解

一、注释 1. #单行注释 2. """ 多行注释 """ 3. pycharm多行注释快捷键:Ctrl+/ 二、缩进 缩进:Tab 反向缩进:Shift+Tab 以上这篇在...