python基础练习之简单用户消费卡管理(非完整版)


写在前面的话:首先要说明的是这个系统未写完整,只实现了几个简单功能,当然其他功能也类似。所用到的知识点也是最简单语法知识。主要是用来作为一个像我这样的初学者来练习用,所以代码写得不那么完美,结构也不一定完美,说不定哪天自己回头来看,自己也觉得写得很垃圾。仅供最初学习者参考,感兴趣的同学可以自己继续补充完整。
一、先来看看现有功能演示(现有功能还有很多待完善的,泪流满面呀,实在没时间改,后面会讲需优化的地方)
         1)用户登录
 
[root@localhost shop]# python main.py
欢迎使用本刷卡系统
please input your user_id:001
please input you password: #这里偷了下懒,做了个密码不回显。
Sucess!Wellcome!
menue:
1      shoping
2      withdraw
3      query
4      user_man
5      comm_man
6      exit
please input your choice:
         2)购物
 
menue:
1      shoping
2      withdraw
3      query
4      user_man
5      comm_man
6      exit
please input your choice:1 #根据提示按1进入购物模式
id     名称    价格    数量
001    apple   2       -490434
002    orange  2       9900
003    pear    3       10000
004    watermelon      3      -399700
005    peach   4       500
please choose the commodity id you want:001
please input the quantity of commodity youwant to buy:800
购物成功    #这里没判断数量是否够,所以看到数量为负数还能购买
if shopcontinue("Y"or"N"): #这里可以选择是否继续
 
         3)取款
 
 
menue:
1      shoping
2       withdraw
3      query
4      user_man
5      comm_man
6      exit
please input your choice:2 #取款模块做得比较简单,输入取款金额就可以啦
please input you want to withdraw: 1000
取款成功,取款金额:1000
当前余额为: 987372
         4)查询
 
menue:
1      shoping
2      withdraw
3      query
4       user_man
5      comm_man
6      exit
please input your choice:3
1:查询购物记录
2:查询取款记录
3:查询存款记录
4:exit
请选择查询类型:2 #这里只实现了查询取款记录
user_id  类别    金额    时间
001    取款    00     2015-09-13 19:44:46
001    取款    1000    2015-09-13 20:31:07
1:查询购物记录
2:查询取款记录
3:查询存款记录
4:exit
请选择查询类型:4
         5)还有用户管理、商品管理等功能,因工作等原因没有继续完成。当然里面有很多细节功能实现这里就不演示了,将在代码中注释。
二、先介绍系统用到的几个文件
[root@localhost shop]# ls -alc |cut -c 43-
commodity.txt  #保存商品信息文件,包括商品id 商品名称、价格、数量
login.py #用户登录模块
main.py #主功能模块
query.py   #查询模块,这里只有实现查询用户取款记录模块
shop.py #购物模块
user.txt #保存用户信息文件,包括用户id、用户名、密码、可用金额
withdraw_log.pkl #用户保存取款信息日志文件,pickle文件类型。
withdraw.py #取款模块

 

 
三、main模块
 
[root@localhost shop]# more main.py
#!/usr/bin/evn python
# -*- coding:utf-8 -*-
  
#主菜单文件
  
#导入相关模块
import sys
import pickle
import getpass
  
#导入自建模块
import login
import shop
import withdraw
import query
  
print '欢迎使用本刷卡系统'
#登陆界面
login_times=1
while True: #wihle实现用户输入用户id和密码不正确可重复再次输入
       user_id=raw_input('please input your user_id:').strip()
       #pwd=raw_input('please input you password:').strip()
#之前实现未对密码操作,更合理的做法是用户输入应回显“*”星号符。
       pwd=getpass.getpass('please input you password:') #实现密码不回显
       if login.login(user_id,pwd):  #实现用户重复输入不能超过三次,避免无限循环
                print 'Sucess!Wellcome!'
                break
       else:
                if login_times<3:
                        login_times+=1
                        continue
                else:
                        print 'you faild above3 times'
                        sys.exit()
while True: #整体一个while循环实现只要用户不主动退出,程序就一直运行
#打印菜单
       print('menue:\n1\tshoping\n2\twithdraw\n3\tquery\n4\tuser_man\n5\tcomm_man\n6\texit')
       while True:
                try:
 #只有此处做了异常处理,所以其他地方输入不合法时会导致程序退出。
                        choice_id =int(raw_input('please input your choice:'))
                        break
                except Exception,e: 
                        print '输入不合法,请输入数字'
  
       if choice_id == 1: #选择1进入购物模式
                while True: #通过while循环实现退出此循环,回到上一个循环
                        #打印可选商品
                        shop.comm_print()
                       comm_id_choice=raw_input('please choose the commodity id you want:')
                       comm_quantity=raw_input('please input the quantity of commodity you wantto buy:')
                       shop.shop(user_id,comm_id_choice,comm_quantity)
                       continue_y_n=raw_input('if shopcontinue("Y"or"N"):')
                        if continue_y_n=='Y' orcontinue_y_n=='y':
                                continue
                        if continue_y_n=='N' orcontinue_y_n=='n':
                                break
       elif choice_id == 2: #选择2进入取款模式
                amount=raw_input('please inputyou want to withdraw: ')
               withdraw.withdraw(user_id,amount)
       elif choice_id == 3: #选择3进入查询模式
                while True:
                        print '1:查询购物记录\n2:查询取款记录\n3:查询存款记录\n4:exit'
                        query_choice=int(raw_input('请选择查询类型:'))
                        if query_choice==1:
                                print "询购物记录"
                        elif query_choice==2:
                               query.q_withdraw_log(user_id)
                        elif query_choice==3:
                                print '查询存款记录'
                        elif query_choice==4:
                               print'exit'
                                break
                        else:
                                print 'byebye'
                                break
  
       elif choice_id == 4: #选择4进入用户管理模式(未实现)
                pass
                print 'user_man'
       elif choice_id == 5: #选择5进入商品管理模式(未实现)
                pass
                print 'comm_man'
       elif choice_id == 6: #选择6退出系统
                print 'exit sucess'
                sys.exit()
       else:
                continue

 

 
四、登录模块
[root@localhost shop]# more login.py
#!/usr/bin/evn python
# -*- coding:utf-8 -*-
#登陆模块
f=file('user.txt','r')
user_id_list=[]
user_pwd_list=[]
  
#将用户名读出并保存到user_id_list列表中
#将用户密码读出并保存到user_pwd_list列表中
for line in f.readlines():
       if '#' in line.split()[0]:
                continue
       else:
               user_id_list.append(line.split()[0])
               user_pwd_list.append(line.split()[2])
f.close()
#定义函数,判断用户输入用户名及密码是否正确
def login(user_id,pwd):
       if user_id in user_id_list:
                if pwd in user_pwd_list:
                        return True
                else:
                        print('pwd error')
       else:
                print('user_id error')

 

 
五、购物模块实现
 
[root@localhost shop]# more shop.py
#!/usr/bin/evn python
# -*- coding:utf-8 -*-
#购物扣款函数
#通过将文件读取出来保存到列表中修改(扣款)后重新保存到文件中来实现
#取款模块也类似这样处理实现
#主要用到:文件读写、字符切割、列表处理
defshop(user_id,commodity_id,commodity_quantity):
       #define commodity_id_list and price_list to save commodity_id
       commodity_id_list=[]
       price_list=[]
       file_comm=file('commodity.txt','r')
       for line in file_comm.readlines():
                if '#' in line: #简单对文件处理从非#号开始读取
                        pass
                else:
                        commodity_id_list.append(line.split()[0])
                       price_list.append(line.split()[2])
       file_comm.close()
       price=''
       for commodity_item in commodity_id_list:
                if str(commodity_id)==(commodity_item):
                       price=price_list[commodity_id_list.index(commodity_item)]
                        #print price
                        break
       if price == '':
                print '选择商品不存在'
                return
       file_comm.close()
       #将用户文件读出
       file_user=file('user.txt','r')
       #defile user_list to save user infomation
       user_list=[]
       for user_line in file_user.readlines():
                user_list.append(user_line)
                if  user_line.split()[0]==user_id:
                       user_list[user_list.index(user_line)]=user_line.split()[0]+'\t'+user_line.split()[1]+'\t'+user_line.split()[2]+'\t'+str(int(user_line.split(
)[3])-int(price)*int(commodity_quantity))+'\n'
       file_user.close()
  
        #将商品文件读出
       file_comm = file('commodity.txt','r')
       comm_list=[]
       for comm_line in file_comm.readlines():
                comm_list.append(comm_line)
                #未判断商品剩余还足量
                ifcomm_line.split()[0]==commodity_id:
                       comm_list[comm_list.index(comm_line)]=comm_line.split()[0]+'\t'+comm_line.split()[1]+'\t'+comm_line.split()[2]+'\t'+str(int(comm_line.split
()[3])-int(commodity_quantity))+'\n'
       file_comm.close()
       print '购物成功'
  
        #将用户文件写入
       file_user=file('user.txt','w')
       file_user.write(''.join(user_list))
       file_user.close()
  
       #将商品文件写入
       file_comm=file('commodity.txt','w')
       file_comm.write(''.join(comm_list))
       file_comm.close()
def comm_print():
       file_comm=file('commodity.txt','r')
       print 'id\t名称\t价格\t数量'
       for line in file_comm.readlines():
                if '#' not in line:
                        print line,
       file_comm.close()

 

 
六、取款模块
 
[root@localhost shop]# more withdraw.py
#!/usr/bin/evn python
# -*- coding:utf-8 -*-
#导入pickle模块
import pickle
import time
#取款模块

 

  
#定义取款函数,参数user_id(用户名)、amount(取款金额)。
def withdraw(user_id,amount):
       f_user=file('user.txt','r')
       user_list=[]
       for user_item in f_user.readlines():
                user_list.append(user_item)
                ifuser_id==user_item.split()[0]:
                        ifint(user_item.split()[3])-int(amount) >=0:

 

#这里实现判断用户金额是否足够,在用户购物时没这项判断
                                user_list[user_list.index(user_item)]=user_item.split()[0]+'\t'+user_item.split()[1]+'\t'+user_item.split()[2]+'\t'+str(int(user_ite
m.split()[3])-int(amount))+'\n'
                               withdraw_log(user_id,amount)
                                print '取款成功,取款金额:%s' %amount
                                print '当前余额为:',str(int(user_item.split()[3])-int(amount))
                                return 'True'
                        else:
                                print '余额不足,取款失败'
                               print '当前余额为:',str(int(user_item.split()[3]))
                                return 'False'
       f_user.close()
       f_user=file('user.txt','w')
       f_user.write(''.join(user_list))
       f_user.close()

 

#定义withdraw_log函数来保存存款日志,参数user_id(用户名)、amount(取款金额)
#这里引用pickle模块的简单用法、及字典简单用法
def withdraw_log(user_id,amount):
       log_dic={}
       ISOTIMEFORMAT='%Y-%m-%d %X'
       new_log=(user_id,'取款',amount,time.strftime(ISOTIMEFORMAT, time.localtime()))
       log_file=file('withdraw_log.pkl','r')
       log_dic=pickle.load(log_file)
       log_file.close()
       #将读出来字典按需求修改
       if log_dic.has_key(user_id):
               log_dic[user_id].append(new_log)
       else:
                log_dic[user_id]=[new_log]
  
       #将修改好的字典dump到文件withdraw_log中
       log_file=file('withdraw_log.pkl','w')
       pickle.dump(log_dic,log_file)
       log_file.close()

 

 
七、查询模块
 
[root@localhost shop]# more query.py
#!/usr/bin/evn python
#-*- coding:utf-8 -*-
import pickle

 

  
#这里只实现了查询取款日志功能,主要还是通过pickle功能来实现
def q_withdraw_log(user_id):
       withdraw_log={}
       f_withdraw_log=file('withdraw_log.pkl','r')
       withdraw_log=pickle.load(f_withdraw_log)
       #print withdraw_log
       f_withdraw_log.close()
       if withdraw_log.has_key(user_id):
                print 'user_id \t类别 \t金额 \t时间'
                for withdraw_log_item inwithdraw_log[user_id]:
                        printuser_id,'\t',withdraw_log_item[1],'\t',withdraw_log_item[2],'\t',withdraw_log_item[3]

 

 
八、总结
此篇仅作为学习python最基础练习之用。

评论关闭