|
发表于 2022-5-4 21:31:37
|
显示全部楼层
本楼为最佳答案
本帖最后由 isdkz 于 2022-5-4 21:39 编辑
使用 logging.info 才是写入日志,你那个是初始化日志,
而且 logging 本来就是你导入的库,不需要在 init_log 中返回的
- import logging
- import os
- import random
- def init_log(path):
- if os.path.exists(path):
- mode = 'a'
- else:
- mode = 'w'
- logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s %(filename)s %(lineno)d %(message)s',
- filename=path,
- filemode=mode
- )
- def guess_number():
- print('********************欢迎进入数字踩踩踩游戏********************')
- init_log('record.txt') # 初始化一次 logging 就可以了
- start = input('数字区间起始值:')
- end = input('数字区间终止值:')
- if not start.isdigit() or not end.isdigit():
- print('您输入的区间数字为非数字字符!!请重新启动程序。')
- exit()
- else:
- start = int(start)
- end = int(end)
- count = 0
- if start == end:
- print('您输入的区间数字相同!!请重新启动程序。')
- exit()
- elif start > end:
- print('您输入的区间数字大小有误!!请重新启动程序。')
- exit()
- else:
- print('所产生的的随机数字区间为:[{}, {}]'.format(start, end))
- random_number = random.randint(start, end)
- while True:
- count += 1
- number = int(input('请继续输入您猜测的数字:'))
- if number not in range(start,end+1):
- print('对不起您输入的数字未在指定区间内!!!')
- continue
- elif number > random_number:
- print('*********')
- print('Higher than the anwser')
- logging.info('Higher than the anwser') # 使用 logging.info
- continue
- elif number < random_number:
- print('*********')
- print('Lower than the anwser')
- logging.info('Lower than the anwser') # 使用 logging.info
- continue
- elif number == random_number:
- print('*********')
- print('恭喜你!只用了{}次就赢得了游戏'.format(count))
- logging.info('恭喜你!只用了{}次就赢得了游戏'.format(count)) # 使用 logging.info
- break
- if __name__ == '__main__':
- guess_number()
复制代码 |
|