Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, random, time
- # 函式
- def output(str , file_obj = None, str2 = ""): # 輸出函式
- print(str)
- if file_obj is not None:
- if str2 != "":
- str = str.replace("的數字", "的數字{}").format(str2)
- file_obj.write(str+"\n")
- def guess(i, ans, begin, end, times): # 猜數字函式
- num = input("第{}次猜測: ".format(i) )
- try:
- val = int(num)
- except ValueError:
- output('=>必須輸入數字(整數)喔. 請輸入一次...', f)
- else:
- if val < begin or val > end:
- output('=>您猜的數字超過範圍囉', f, val)
- elif val < ans:
- output('=>您猜的數字比答案小', f, val)
- elif val > ans:
- output('=>您猜的數字比答案大', f, val)
- elif val == ans:
- output('=>恭喜,您猜對數字了!', f, val)
- return True # break
- else:
- output('=>Debug ### error', f, val) # 除錯用
- return False
- if i == times:
- output('=>正確答案應為{}'.format(ans), f)
- return False
- # 初始化變數
- times = 7 # 猜的次數
- begin = 1 # 亂數起始值
- end = 100 # 亂數結束值
- dtfmt = "%Y/%m/%d %H:%M:%S" # 日期時間格式
- logfile = "log.txt" # 記錄檔檔名
- logenc = 'UTF-8' # 記錄檔編碼
- # 程式開始
- choice = 'Y'
- while choice == 'Y':
- os.system('cls')
- f = open(logfile, 'a', encoding=logenc) # 開啟記錄檔
- output(time.strftime(dtfmt), f)
- answer = int(random.uniform(begin, end)) # 答案
- output('=>請從{}-{}的數字中間猜一個數字,只能猜{}次[提示:{}]'.format(begin, end, times, answer), f)
- for i in range(1, times + 1):
- if guess(i, answer, begin, end, times):
- break
- choice = input("\n要再玩一次嗎?(Y/N):").upper()
- f.close() # 關閉檔案
Add Comment
Please, Sign In to add comment