10.8 实践项目:调试硬币抛掷
项目要求:书中给了一段代码,隐藏了一些bug,用logging调试并找出问题所在
#! python3
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s,
%(levelname)s - %(message)s')
import random
def guess_fun():
global guess
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
guess = ''
guess_fun()
toss = random.choice(['heads', 'tails']) # 0 is tails, 1 is heads
logging.info('toss is %s, guess is %s' % (toss, guess))
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess = ''
guess_fun()
logging.info('toss is %s, guess is %s' % (toss, guess))
if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.')
思路:
- 基本上bug认真读读代码就可以看出来;但作为练习,还是要把logging插入到合适的位置
- logging作为调试,虽然用起来较麻烦,但是要习惯
环境:python3
想做这个系列文章,就是因为当时看这本书时,想看看网上有没更优美的解决,但是略难找到。所以就把自己的项目练习放在了一个txt文件中,现在把练习代码放到这里,有不足之处希望大家能给出指导意见及相互交流、提升。