daily pastebin goal
20%
SHARE
TWEET

Untitled

a guest Mar 14th, 2018 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import os, random, time
  2.  
  3. # 函式
  4. def output(str , file_obj = None, str2 = ""): # 輸出函式
  5.     print(str)
  6.     if file_obj is not None:
  7.         if str2 != "":
  8.             str = str.replace("的數字", "的數字{}").format(str2)
  9.         file_obj.write(str+"\n")
  10.  
  11. def guess(i, ans, begin, end, times): # 猜數字函式
  12.     num = input("第{}次猜測: ".format(i) )
  13.  
  14.     try:
  15.         val = int(num)
  16.     except ValueError:
  17.         output('=>必須輸入數字(整數)喔. 請輸入一次...', f)
  18.     else:
  19.         if val < begin or val > end:
  20.             output('=>您猜的數字超過範圍囉', f, val)
  21.         elif val < ans:
  22.             output('=>您猜的數字比答案小', f, val)
  23.         elif val > ans:
  24.             output('=>您猜的數字比答案大', f, val)
  25.         elif val == ans:
  26.             output('=>恭喜,您猜對數字了!', f, val)
  27.             return True # break
  28.         else:
  29.             output('=>Debug ### error', f, val) # 除錯用
  30.             return False
  31.  
  32.     if i == times:
  33.         output('=>正確答案應為{}'.format(ans), f)
  34.     return False
  35.  
  36. # 初始化變數
  37. times = 7 # 猜的次數
  38. begin = 1 # 亂數起始值
  39. end   = 100 # 亂數結束值
  40. dtfmt = "%Y/%m/%d %H:%M:%S" # 日期時間格式
  41. logfile = "log.txt" # 記錄檔檔名
  42. logenc = 'UTF-8' # 記錄檔編碼
  43.  
  44. # 程式開始
  45. choice = 'Y'
  46. while choice == 'Y':
  47.     os.system('cls')
  48.  
  49.     f = open(logfile, 'a', encoding=logenc) # 開啟記錄檔
  50.     output(time.strftime(dtfmt), f)
  51.  
  52.     answer = int(random.uniform(begin, end)) # 答案
  53.     output('=>請從{}-{}的數字中間猜一個數字,只能猜{}次[提示:{}]'.format(begin, end, times, answer), f)
  54.  
  55.     for i in range(1, times + 1):
  56.         if guess(i, answer, begin, end, times):
  57.             break
  58.     choice = input("\n要再玩一次嗎?(Y/N):").upper()
  59.  
  60. f.close() # 關閉檔案
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top