新猜數字遊戲--查看歷史記錄
阿新 • • 發佈:2017-05-29
dump span utf style col pri 就會 tor 再次
猜數字遊戲,就是隨機生成一個數字,猜這個數字的大小,輸入的值會有提醒比真值大還是小。這個新是說通過加入隊列來實現了可以查看之前輸入過得值。
1 # encoding = utf-8 2 from random import randint 3 # 引入隊列 4 from collections import deque 5 6 N = randint(0,100) 7 # history隊列能夠存儲5個值 8 history = deque([],5) 9 10 def guess(k): 11 if k == N: 12 print ‘right‘ 13return True 14 if k < N: 15 print ‘%s is less-than N‘ % k 16 else: 17 print ‘%s is bigger-than N‘ % k 18 return False 19 20 while True: 21 line = raw_input("please input a number:") 22 if line.isdigit(): 23 k = int(line) 24 # 通過append方法將新輸入的值存儲到history中25 history.append(k) 26 if guess(k): 27 break 28 # 通過輸入相應的字符來查看輸入歷史 29 elif line == ‘history‘ or line == ‘h?‘: 30 print list(history) 31 32 33
這種方式只能暫時將數值保存到相應的程序中,當再次打開程序時就會作廢。可以利用pickle包中的函數來實現將信息存儲到文件或者從文件中讀取信息。
1 # 引入包2 import pickle 3 # 打開文件並將信息寫入 4 pickle.dump(q,open(‘history‘,‘w‘)) 5 # 從文件中讀取並賦值給q2 6 q2 = pickle.load(open(‘history‘))
新猜數字遊戲--查看歷史記錄