Python編程快速上手-讓繁瑣工作自動化-第二章習題及其答案
1、布爾數據類型的兩個值是什么?如何拼寫?
答:True和False,使用大寫的T和大寫的F,其他字母是小寫。
2、3個布爾操作符是什么?
答:and、or和not。
3、寫出每個布爾操作符的真值表(也就是操作數的每種可能組合,以及操作的結果)
答:
and:
True and True -> True
True and False -> False
False and True -> False
Fasle and False -> False
or:
True or True -> True
True or False -> True
False or True -> True
False or False -> False
not:
not True -> False
not False -> True
4、以下表達式求值的結果是什么?
4.1、( 5 > 4 ) and ( 3 == 5 )
4.2、not ( 5 > 4 )
4.3、( 5> 4 ) or ( 3 == 5 )
4.4、not (( 5 > 4 ) or ( 3 == 5 ))
4.5、( True and True ) and ( True == False )
4.6、( not False ) or ( not True )
答:4.1、
(5>4) and (3 == 5)
TrueandFalse
False#最終結果
4.2、not (5 > 4)notTrue
False#最終結果
4.3、
(5> 4 ) or ( 3 == 5)
TrueorFalse
True#最終結果
4.4、not (( 5 > 4 ) or ( 3 == 5))not (True orFalse)notTrue
False#最終結果
4.5、
( Trueand True ) and ( True ==False )
TrueandFalse
False#最終結果
4.6、
(not False ) or ( notTrue )
TrueorFasle
True#最終結果
5、6個比較操作符是什么?
答:==、!=、、<=和>=。
6、等於操作符和賦值操作符的區別是什么?
答:==是等於操作符,它比較兩個值,求值為一個布爾值,而=是賦值操作符,將值保存在變量中。
7、解釋什么是條件,可以在哪里使用條件?
答:條件是一個表達式,它用於控制流語句中,求值為一個布爾值。
8、識別這段代碼中的3個語句塊
spam =0if sapm == 10:print('eggs')if spam > 5:print('bacon')else:print('ham')print('spam')print('spam')
答:3個語句塊是if語句中的全部內容,以及print('bacon')和print('ham')這兩行。print('eggs')if spam > 5:print('bacon')else:print('ham')print('spam')
9、編寫代碼,如果變量spam中存放1,就打印Hello,如果變量中存放2,就打印Howdy,如果變量中存放其它值,就打印Greetings
答:#!/usr/bin/env python3#-*- coding:utf-8 -*-#Author: davie
spam = input("請輸入1或者2->:")ifspam.isdigit():
spam=int(spam)if spam == 1:print("Hello %s"%spam)elif spam == 2:print("Howdy %s"%spam)else:print("Greetings!")else:print("您輸入的不是數字1或者2")
10、如果程序陷在一個無限循環中,你可以按什么鍵?
答:按Ctrl-C來停止陷在無線循環中的程序。
11、break和continue之間的區別是什么?
答:
break:
終止整個循環:當循環或判斷執行到break語句時,即使判斷條件為True或者序列尚未完全被歷遍,都會跳出循環或判斷。
continue
跳出當次循環。當循環或判斷執行到continue語句時,continue后的語句將不再執行,會跳出當次循環,繼續執行循環中的下一次循環。
12、在for循環中,range(10)、range(0,10)和range(0,10,1)之間的區別是什么?
答:
效果一樣,都是打印出0-9的數字。range(10)調用產生的范圍是從0直到(但不包括)10,range(0,10)明確告訴循環從0開始,range(0,10,1)
明確告訴循環每次迭代變量加1。
13、編寫一小段程序,利用for循環,打印出從1到10數字。然后利用while循環,編寫一個等價的程序,打印出從1到10的數字
#編寫一小段程序,利用for循環,打印出從1到10數字。
for i in range(1,11):print('for loop : %s'%i)#利用while循環,編寫一個程序,打印出從1到10的數字
count =0while count <10:
count+= 1
print("while loop:%s"%count)
14、如何在名為spam的模塊中,有一個名為bacon()的函數,那么在導入spam模塊后,如何調用它?
答:
from spam import bacon
spam.bacon()
15、附加題:在網上查找round()和abs()函數,弄清楚它們的作用。在交互式環境中嘗試使用它們
答:
round():四舍五入
abs():求絕對值>>> round(3.1414926,3)3.141
>>> round(3.1415926,3)3.142
>>> round('4.5678',1)
Traceback (most recent call last):
File"", line 1, in TypeError: type str doesn't define __round__ method
>>>
>>> abs(-10)10
>>> abs(8)8
>>> abs('09')
Traceback (most recent call last):
File"", line 1, in TypeError: bad operand typefor abs(): 'str'
>>>這兩個都必須接受數字類型的數據,否則會報錯。