《python编程快速上手 让繁琐工作自动化》第十章习题+实践答案

1 习题

1.assert(spam >= 10, ‘The spam variable is less than 10.’)
2.assert(eggs.lower() != bacon.lower(), ‘The eggs and bacon variables are the same!’)
或assert(eggs.upper() != bacon.upper(), ‘The eggs and bacon variables are the same!’)
3.assert(False, ‘This assertion always triggers.’)
4.为了能调用logging.debug(),必须在程序开始时加入以下两行:
import logging
logging.basicConfig(level=logging.DEBUG, format=’ %(asctime)s -
%(levelname)s - %(message)s’)
5.为了能利用logging.debug() 将日志消息发送到文件programLog.txt 中,必须
在程序开始时加入以下两行:
import logging
logging.basicConfig(filename=‘programLog.txt’, level=logging.DEBUG,
format=’ %(asctime)s - %(levelname)s - %(message)s’)
6.DEBUG、INFO、WARNING、ERROR 和CRITICAL
7.logging.disable (logging.CRITICAL)
8.可以禁用日志消息,不必删除日志函数调用。可以选择禁用低级别日志消
息。可以创建日志消息。日志消息提供了时间戳。
9.Step 按扭让调试器进入函数调用。Over 按钮将快速执行函数调用,不会单
步进入其中。Out 按钮将快速执行余下的代码,直到走出当前所处的函数。
10.在点击Go 后,调试器将在程序末尾或断点处停止。
11.断点设在一行代码上,在程序执到到达该行时,它导致调试器暂停。
12.选中代码行,鼠标右击,选择sert breakpoint

2 实践项目

下面程序的意图是一个简单的硬币抛掷猜测游戏。玩家有两次猜测机会(这
是一个简单的游戏)。但是,程序中有一些缺陷。让程序运行几次,找出缺陷,使
该程序能正确运行。

缺陷代码:

import random
guess = ''
while guess not in ('heads', 'tails'):
    print('Guess the coin toss! Enter heads or tails:')
    guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == guess:
    print('You got it!')
else:
    print('Nope! Guess again!')
    guesss = input()
    if toss == guess:
	    print('You got it!')
    else:
	    print('Nope. You are really bad at this game.')

修正后:

import random
import logging 
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s -%(levelname)s - %(message)s')
guess = ''
guess_dict={}
while guess not in ('heads', 'tails'):
    print('Guess the coin toss! Enter heads or tails:')
    guess = input()
if guess=='heads':
    guess_dict[guess]=1
elif guess=='tails':
    guess_dict[guess]=0    
logging.debug(guess)

toss = random.randint(0, 1) # 0 is tails, 1 is heads
logging.debug(toss)
logging.debug(guess_dict.get(guess))
 
if toss == guess_dict.get(guess):
    print('You got it!')
else:
    print('Nope! Guess again!')
    guesss = input()
    logging.debug(toss)
    if toss == guess_dict.get(guess):
        print('You got it!')
        logging.debug(guess_dict.get(guess))
    else:
        print('Nope. You are really bad at this game.')

思路:
运行多次后,发现一次也没才对,运气应该没这么差劲吧!
查看代码后发现,guess获取的值是’heads’和’tails’,toss获取则是0和1,将guess的值存入字典中,guess_dict={“heads”:1,“tails”:0}完美解决。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值