模块化编程

#用"from ... import *"来执行代码模块中的函数,就不需要提到模块名,而且可以使用模块中定义的变量
#如果你需要使用完全限定名(FQN)来用模块名限定函数名(这也是Python里推荐的做法),可以用"import..."
from transaction_module import *
#import transaction_module
#items = ["DONUT","LATTE","FILTER","MUFFIN"]
#prices = [1.50,2.0,1.80,1.20]
running = True

while running:
    option = 1
    for choice in items:
        print(str(option)+"."+choice)
        option = option + 1
    print(str(option)+".Quit")
    
    choice = int(input("your choice is:"))
    if choice == option:
        running = False
    else:
        credit_card = int(input("your credit card is:"))
        save_transaction(prices[choice-1]*100,credit_card,items[choice-1])
        print("Yes")
#模块文件
#transaction_module.py

#import re
def save_transaction(price,credit_card,item):
    file = open("transaction.txt","a")
    file.write("%16s%07d %16s\n"%(credit_card,price,item))
    file.close()

def pare_sale_info():
    file = open("sale_info.txt")
    a = []
    for each_line in file:
        (card_num,item_num) = each_line.split(" ")
        a.append([int(card_num),int(item_num)])
    return(a)

items
= ["DONUT","LATTE","FILTER","MUFFIN"] prices = [1.50,2.0,1.80,1.20] #后面仅做模块调试使用 sale_info = pare_sale_info() i = 0 for each_info in sale_info: save_transaction(prices[each_info[1]-1]*100,each_info[0],items[each_info[1]-1]) #print(item)

操作相关的文件:

#sale_info.txt

6382746238764830     1
6382746238764840     2
6382746238764850     3
6382746238764860     4
6382746238764870     1
6382746238764880     2
6382746238764890     3
6382746238764900     4
6382746238764910     1
6382746238764920     2
6382746238764930     3
6382746238764940     4
6382746238764950     1
6382746238764960     2
6382746238764970     3
#transaction.txt

63827462387648300000150            DONUT
63827462387648400000200            LATTE
63827462387648500000180           FILTER
63827462387648600000120           MUFFIN
63827462387648700000150            DONUT
63827462387648800000200            LATTE
63827462387648900000180           FILTER
63827462387649000000120           MUFFIN
63827462387649100000150            DONUT
63827462387649200000200            LATTE
63827462387649300000180           FILTER
63827462387649400000120           MUFFIN
63827462387649500000150            DONUT
63827462387649600000200            LATTE
63827462387649700000180           FILTER
63827462387648300000150            DONUT
63827462387648400000200            LATTE
63827462387648500000180           FILTER
63827462387648600000120           MUFFIN

 

posted @ 2017-08-20 21:21  aWolfMan  阅读(236)  评论(0编辑  收藏  举报