隨機生成雙色球號碼和商品管理python程式
阿新 • • 發佈:2018-12-04
1、寫一個程式,輸入N就產生N條雙色球號碼
紅球 6 01-33
藍球 1 01-16
產生的雙色球號碼不能重複,寫到一個檔案裡面,每一行是一條
紅球: 01 03 05 07 08 18 藍球:16
紅球需要排序,是升序
2、寫一個商品管理的程式:
1、新增商品
商品名稱:商品已經存在的話,要提示
商品價格: 校驗,是大於0的數字
商品數量:校驗,只能是大於0的整數
2、刪除商品
商品名稱:商品不存在的話,要提示
3、檢視商品
顯示所有的商品資訊
4、退出
def add_product():
pass
def del_product():
pass
def show_product():
pass
choice = input('請輸入你的選擇:')
程式碼1:
#_author:'ZYB' #data:2018/12/3 import random def RedBall(N): R = set() while len(R) != N: start = random.randint(1, 33) R.add('%02d' % start) L = sorted(list(R)) result = ' '.join(L) return result def DoubleColorBall(count): results = set()while len(results) != count: starts = RedBall(6) end = random.randint(1, 16) res = '紅球:%s 藍球:%02d\n' % (starts, end) results.add(res) with open('shuangseqiu.txt', 'w', encoding='utf-8') as fw: fw.writelines(results) DoubleColorBall(500)
程式碼2
#_author:'ZYB' #data:2018/12/3 import json def readjson(): try: with open('product.json', 'a+', encoding='utf-8') as f: res = json.load(f) # load可以讀檔案 return res except json.decoder.JSONDecodeError: #不加此句,json讀取空檔案會報錯! dic={} writejson(dic) return dic def writejson(dic): fw = open('product.json', 'w', encoding='utf-8') json.dump(dic, fw, indent=4, ensure_ascii=False) fw.close() def add_product(name,prices,counts): res = readjson() d1 = {} d2 = d1.setdefault(name, {}) d2.setdefault('price', prices) d2.setdefault('count', counts) if res.get(name): print('商品已存在') else: res[name] = d1[name] writejson(res) def del_product(name): res = readjson() if res.get(name): res.pop(name) writejson(res) else: print('商品不存在') def show_product(): res = readjson() print(res) def ispostiveNum(N): if N.replace(".", '').isdigit() and N != '0': if N.count(".") == 0 or N.count(".") == 1: return True else: return False def ispositiveinteger(N): N = str(N) if N.isdigit()and N != '0': return True else: return False choice = input('請輸入你的選擇[1:新增商品;2:刪除商品;3:顯示商品;4:退出]:') if choice == '1': name = input('請輸入商品名稱:') price = input('請輸入商品價格:') if ispostiveNum(price): count = input('請輸入商品數量:') if ispositiveinteger(count): add_product(name,price,count) else: print('輸入商品數量格式不正確!') else: print('輸入商品價格格式不正確!') elif choice == '2': name = input('請輸入要刪除商品的名稱:') del_product(name) elif choice == '3': show_product() else: pass