模擬購物和信用卡

   很久沒寫博文了,看了下距離before篇的時間確實有點長,真是感受時間愈來愈不夠用了…… 好了不扯了,進入主題:python

   先交代一下,此程序純粹是爲了練習Python各類元素的用法而假想出來的,距離如今已有段時間,此時筆者只是簡單的掌握了列表、字典、模塊(sys、os、pickle)文件讀寫等基本語法。
git


功能模型思路:安全

   一、錢、沒錢怎麼買東西…… 因此每次購物須要帶錢(現金+信用卡)
app

   二、既然是購物程序那麼要有商品列表和價格的對照表以便用戶購買,用戶不能買超出本身支付能力的商品,購買商品成功應當加入用戶的購物列表,而且實時的顯示用戶的餘額,購物刷卡沒有手續費。
ide

   三、當用戶現金不夠時能夠用信用卡支付,信用卡付款金額 = 商品價格 - 現金(身上的錢)
函數

   四、信用卡能夠提現金,可是有手續費。
ui

   五、應當提供還款接口。
spa

   六、能夠查看信用卡的明細,好比說什麼時間買過什麼東西,花了多少錢等……
rest

   七、退出
orm


邏輯模型思路:

   一、購物

       print 購物列表,任意用戶能夠光臨,money爲用戶的全部錢,quit爲退換主菜單,若是現錢不夠能夠刷卡

   二、提現

       10%的利息

   三、還錢

   四、查看帳單(函數和Pickle)

       最大額度 = 15000

       可用額的 = 11000   (購買商品不能大於此額度)

       虧欠金額 = 4000   (此金額不能大於15000)

       ######################################

       DATE    EVENT    DATA     INTEREST

        1      car      20000       0

        2      還款    -20000       0

        3      提現     1000       100

   五、退出


代碼以下:

#!/usr/bin/env python
#Author: Created by soulboy
#Function: Shopping with a credit card
import sys
import os
import pickle
salary = int(raw_input("Inpuet your salary:").strip()) #初始化每次購物的現金
def dump():                            #把pickle.dump方法定義爲函數方便調用
    output = file('data.pkl','wb')
    pickle.dump(maxoverdraft,output) #信用卡最大透支額度
    pickle.dump(available,output)    #可用額度
    pickle.dump(overdraft,output)    #虧欠額度
    pickle.dump(bill,output)         #用bill字典來保存以日期爲Key保存信用卡的明細
    output.close()
f = str(os.path.isfile('data.pkl'))      #定義pickle的文件data,用來保存序列化數據對象
if 'False' in f:             #若是程序是首次運行,會初始化以下對象並保存至當前目錄data.pkl文件中
    maxoverdraft = 15000
    available = 15000
    overdraft = 0
    bill = {}
    dump()
def load():             #從data.pkl文件中按順序讀取序列化數據對象並從新賦值
    global maxoverdraft     #聲明全局變量方便在局部變量在函數外調用
    global available
    global overdraft
    global bill
    pkl_file = file('data.pkl','rb')
    maxoverdraft = pickle.load(pkl_file)
    available = pickle.load(pkl_file)
    overdraft = pickle.load(pkl_file)
    bill = pickle.load(pkl_file)
    pkl_file.close()
def information():          #定義信息方便各功能模塊重複調用
    print '''
maxoverdraft = %s $         #最大透支額度
available = %s $            #可用額度
overdraft = %s $''' %(maxoverdraft,available,overdraft) #虧欠額度
def welcome():              #主菜單函數
    print '''[1]:Go shopping !
[2]:Withdraw money !
[3]:Repayment !
[4]:Credit card list !
[5]:Exit !
            '''
def authentication():           #密碼認證函數,本程序中信用卡號爲:soulboy,密碼爲:soulboy
    while True:
        count = 0
        account = raw_input("Please input your username:")
        if account == 'soulboy':
            password = raw_input("Please input your password:")
            if password == 'soulboy':break
            while password != 'soulboy':    #實時顯示剩餘密碼重試次數
                count += 1
                chance = 3 - count
                password = raw_input("Error password and try again,you have %s chance:"%(chance))
                if count == 3:break
            if count == 3:continue
            else:break
        else:
            print "Sorry, the %s is not exist and please check yourself:" % account
while True:
    welcome()
    print "Your Salary: %s $" % salary
    option = raw_input("Based on the digital option:").strip()
    if option == '1':
        shoplist = []
        while True:
            products = ['house','car','phone','computer','clothes']  #商品列表中的元素依次與價格列表中的元素一一對應
            pirce = [600000,200000,4000,8000,200]
            print "########################## The list of goods ##########################"
            for p in products:
                print "%s \t %s" %(p,pirce[products.index(p)])   #經過商品列表的座標取出商品對應的價格
            choice = raw_input("please choice by it's name:")
            result = products.count(choice)
            if choice == 'quit':
                print '''
Your shopping list: %s
Remaining salary: %s
welcome to next shopping
#######################################################################''' % (shoplist,salary)  #顯示購物列表、剩餘現金
                break
            elif result == 0:                           #商品名稱不存在提示重輸
                print " %s not in goods list, input right name:" % choice
                continue
            pgoods = pirce[products.index(choice)]
            if pgoods > salary:                          #當商品價格大於現金
                selection = raw_input("not engouh money for %s, you will use credit card ?[yes] or [no]:" %(choice)) #是否刷卡
                if selection == 'yes':
                    authentication()        #安全認證
                    load()              #讀取data.pkl文件中
                    total = salary + available
                    if total >= pgoods:      #當信用卡和現金大於商品價格時
                        date = raw_input("Input your date:") #輸入交易日期
                        event = choice      #事件
                        interest = 0        #利息
                        data = pgoods - salary  #數據
                        bill[date] = [event,data,interest] #以日期key其餘元素爲value保存至字典中
                        overdraft = overdraft + data
                        available =  available - pgoods + salary   
                        dump()          #保存至data.pkl文件中
                        shoplist.append(choice) #添加商品至購物列表
                        salary = 0      #現金清0
                        print '''%s add your shopping list %s
salary left:%s $
credit car left: %s $'''    %(choice,shoplist,salary,available)
                    else:               #錢不夠
                        print "Sorry not engouh money ! "
            else:
                salary = salary - pgoods        #現金大於產品價格
                shoplist.append(choice)
                print "%s add your shopping list %s ,and your money left:%s $"  %(choice,shoplist,salary)
    elif option == '2': #提現金
        authentication()
        date = raw_input("Input the date:") #日期
        while True:
            load()
            information()
            print '''Your Salary: %s $
withdrawal:[yes]
quit:[no]''' % salary
            select = raw_input("your choice:[yes] or [no]") #是否繼續
            if select == 'no':break
            withdrawal = int(raw_input("Input the withdrawal amount and the fee is 10%:"))
            if withdrawal > available:           #提取金額不能大於可用金額
                print "Beyond the maximun amount:"
                continue
            else:
                salary += withdrawal            #現金增長
                data = withdrawal + withdrawal / 10
                interest =  withdrawal / 10     #手續費爲提取金額的10%
                available = available - data
                event = "remove"
                overdraft += data
                bill[date] = [event,data,interest]
                dump()                  #和以前同樣
                print "The sucess of the transaction and you salary: %s $" % salary
                continue
    elif option == '3':     #還錢接口
        date = raw_input("Input the date:") #日期
        authentication()
        while True:
            load()
            information()
            print '''Your Salary: %s $
repayment:[yes]
quit:[no]''' % salary
            select = raw_input("your choice:[yes] or [no]")
            if select == 'no':break
            repayment = int(raw_input("Input the repayment amount:"))
            if repayment > salary:               #還錢金額不能大於你現金
                print "You don't have so much!"
            elif repayment > overdraft:          #還錢金額最多等於虧欠額度
                excess = repayment - overdraft
                salary = salary - repayment + excess
                event = "back"
                data = -overdraft
                interest = 0
                available += overdraft
                overdraft -= overdraft
                bill[date] = [event,data,interest]
                dump()
            else:                       #正常狀況下
                salary = salary - repayment
                available += repayment
                overdraft -= repayment
                event = "back"
                data = -repayment
                interest = 0
                bill[date] = [event,data,interest]
                dump()
    elif option == '4': #查看信用卡明細
        load()
        print '''#######################################################################
DATE        EVENT       DATA        INTEREST'''
        for k,v in bill.items():
            print "%s       %s      %s      %s" %(k,v[0],v[1],v[2])
        information()
        print "#######################################################################"
        dump()
    elif option  == '5':    #退出
        sys.exit()


補充說明:日期這塊是手動輸入的,當時還沒看到date模塊,使用的時候每第二天期儘可能別重複,安全認證函數在查看信用卡明細的時候沒有調用主要是爲了方便查看,日期忘記排序了,運行效果應該以下:

071810307.png

相關文章
相關標籤/搜索