- 習(xí)題27:記住邏輯關(guān)系
*心得:
①理解會比強(qiáng)記更牢靠;
②后面的比較復(fù)雜的布爾運(yùn)算其實(shí)就是 與或非 + 4個等于判定 + 真假值 的組合,所以真值表一定要非常熟悉;
③網(wǎng)上找到的一個速記口訣:真真得真(與運(yùn)算),假假得假(或運(yùn)算),同假異真(異或運(yùn)算)。
- 習(xí)題28:布爾表達(dá)式練習(xí)
# -- cdoing:utf-8 --
# 習(xí)題 28:布爾表達(dá)式練習(xí)
print(True and True) # True
print(False and True) # False
print(1 == 1 and 2 == 1) # False
print('test' == 'test') # True
print(1 == 1 or 2 != 1) # True
print(True and 1 == 1) # True
print(False and 0 != 0) # False
print(True or 1 == 1) # True
print('test' == 'testing') # False
print(1 != 0 and 2 == 1) # False
print('test' != 'testing') # True
print('test' == 1) # False
print(not (True and False)) # True
print(not (1 == 1 and 0 != 1)) # False
print(not (10 == 1 or 100 == 1000)) # True
print(not (1 != 10 or 3 == 4)) # False
print(not ('test' == 'testing' and 'Zed' == 'Cool guy')) # True
print(1 == 1 and not ('testing' == 1 or 1 == 0)) # True
print('chunky' == 'bacon' and not (3 == 4 or 3 == 3)) # False
print(3 == 3 and not ('testing' == 'testing' or 'Python' == 'Fun')) # False
*心得:
①在運(yùn)算之前應(yīng)該先瀏覽一遍整個運(yùn)算式子,再按照真值表中的基本運(yùn)算單元去拆解求真值;
②《笨辦法學(xué)Python》沒有強(qiáng)調(diào)的是括號的優(yōu)先級:如果有括號,優(yōu)先進(jìn)行括號內(nèi)的布爾表達(dá)式。如果括號內(nèi)有多個層級的括號,應(yīng)該由內(nèi)向外進(jìn)行計(jì)算。可參考數(shù)學(xué)計(jì)算的多層級括號計(jì)算次序。== 、!= 判斷的運(yùn)算,等號兩邊也是可能包含括號的,比如 (3 == 2 and 6 != 7) == (6 > 7 or 6 >3),not( )、( ) and/or ( )都應(yīng)該先從括號內(nèi)的運(yùn)算開始。
加分習(xí)題:
27.1 Python 里還有很多和 != 、 == 類似的操作符. 試著盡可能多地列出 Python 中的等價(jià)運(yùn)算符。例如 < 或者 <= 就是。
print(7 < 8) # True
print(7 <= 7) # True
print(7 > 8) # False
print(7 >= 7) # True
print(7 != 7) # False
- 習(xí)題29:如果if
# --coding:utf-8 --
# 習(xí)題 29:如果 if
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
加分習(xí)題:
29.1 你認(rèn)為 if 對于它下一行的代碼做了什么?
if給下一行提供了執(zhí)行與否的判定,如果if False,下一行語句不執(zhí)行(跳過)
29.2、29.3 為什么 if 語句的下一行需要 4 個空格的縮進(jìn)?如果不縮進(jìn),會發(fā)生什么事情?
下一行執(zhí)行的前提是if True,縮進(jìn)的代碼會在if True的條件下執(zhí)行。如果不縮進(jìn),代碼運(yùn)行會報(bào)錯。(總覺得《笨辦法學(xué)Python》的答案是回答“為什么if條件句后要有個冒號”這個問題的。我覺得if條件句、while-loop和for-loop中關(guān)于代碼縮進(jìn)和不縮進(jìn),縮進(jìn)多少,是個很值得注意和探究的問題,很多時候循環(huán)中差一個縮進(jìn)就會得到完全不同的結(jié)果了。)
29.4 把習(xí)題 27 中的其它布爾表達(dá)式放到if 語句
中會不會也可以運(yùn)行呢?
if False/if True 會根據(jù)if 后面的邏輯表達(dá)式的最終結(jié)果進(jìn)行判斷。
- Else 和 If
# -- coding:utf-8 --
# 習(xí)題 30:Else和if
people = 30
cars = 40
buses = 15
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if buses > cars:
print("That's too many buses.")
elif buses < cars:
print("Maybe we could take the buses.")
else:
print("We still can't decide.")
if people > buses:
print("Allright, let's just take the buses.")
else:
print("Fine, let's stay home then.")
加分習(xí)題:
30.1 猜想一下 elif 和 else 的功能
if-else 語句塊類似于簡單的if 語句,但其中的else 語句讓你能夠指定條件測試未通過時要執(zhí)行的操作。
if-elif-else結(jié)構(gòu),python只執(zhí)行if-elif-else結(jié)構(gòu)中的一個代碼塊,它依次檢查每個條件測試,直到遇到通過了的條件測試。測試通過后,python將執(zhí)行緊跟在它后面的代碼,并跳過余下的測試。
30.3 試著寫一些復(fù)雜的布爾表達(dá)式,例如 cars > people and buses < cars。
if cars > people and buses < cars:
print("We should take the cars.")
- 作出決定
# -- coding:utf-8 --
# 習(xí)題31:作出決定
print( "You enter a dar room with doors.\nDo you go through door #1 or door #2?")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a cheese cake.\nWhat do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input("> ")
if bear == '1':
print("The bear eats your face off. Good job!")
elif bear == '2':
print("The bear eats your legs off. Good job!")
else:
print("Well, doing %s is probably better. Bear runs away." % bear)
elif door == '2':
print("You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")
insanity = input("> ")
if insanity == '1' or insanity == '2':
print("Your body survives powered by a mind of jello. GOod job!")
else:
print("The insanity rots your eyes into a pool of muck. Good job!")
else:
print("You stumble around and fall on a knife and die. Good job!")
心得:
嵌套時候的縮進(jìn)太重要了。準(zhǔn)確的縮進(jìn)能夠準(zhǔn)確的傳達(dá)層次,代碼的易讀性也比較高。
- 循環(huán)和列表
# -- coding:utf-8 --
# 習(xí)題 32:循環(huán)和列表 for-loop
hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weight = [1, 2, 3, 4]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print("This is count %d" % number) # 使用格式化字符串
for number in the_count:
print("This is count " + str(number)) # 使用變量
# same as above
for fruit in fruits:
print("A fruit of type: %s" % fruit) # 格式化字符串
for fruit in fruits:
print("A fruit of type: " + fruit)
# also we can go through mixed lists too
# *notice we have to use %r since we don't konw what's in it
for i in change:
print("I got %r" % i) # 格式化字符串
# we can also build lists, first start with an empty one
elements = [] # 創(chuàng)建空列表
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding %d to the list." % i)
elements.append(i)
# now we can print them out too
for i in elements:
print("Elements was: %d" % i)
加分習(xí)題:
32.1 注意一下 range 的用法。查一下 range 函數(shù)并理解它。
range()可以生成一系列的數(shù)字,函數(shù)range()包含兩個參數(shù),讓python從指定的第一個值開始數(shù),并在到達(dá)指定的第二個值后停止,因此輸出不包含第二個值。
32.2 在第 22 行,你可以可以直接將 elements 賦值為range(0,6),而無需使用 for 循環(huán)?
elements_1 = list(range(1,3))
32.3 在 Python 文檔中找到關(guān)于列表的內(nèi)容,仔細(xì)閱讀以下,除了 append 以外列表還支持哪些操作?
①修改:hairs[0] = 'green'
②永久刪除指定索引元素:del hairs[0]
③刪除(彈出)最后一個元素:color_1 = hairs.pop()
④刪除指定值(列表中的第一個):hairs.remove('blue')
⑤對列表進(jìn)行永久性排序:hairs.sort()
⑥對列表進(jìn)行臨時排序:hairs_sorted = sorted(hairs)
- While 循環(huán)
# coding=utf-8
# 習(xí)題33:while循環(huán) while-loop
# while循環(huán)會一直執(zhí)行它下面的代碼片段,直到它對應(yīng)的布爾表達(dá)式為False時才會停下來
i = 0
numbers = []
while i < 6:
print("At the top i is %d" % i)
numbers.append(i)
i += 1 # 遞增,有結(jié)束while循環(huán)的條件
print("Numbers now: ", numbers)
print("At the bottom i is %d" % i)
print("The numbers: ")
for num in numbers:
print(num)
加分習(xí)題
33.1 /33.2/33.3將這個 while 循環(huán)改成一個函數(shù),將測試條件(i < 6)中的 6 換成一個變量。
i = 0
end_num = 9
step_num = 2 # 設(shè)置步長為2
numbers = []
while i < end_num:
print("At the top i is %d" % i)
numbers.append(i)
i += step_num # 遞增,有結(jié)束while循環(huán)的條件
print("Numbers now: ", numbers)
print("At the bottom i is %d" % i)
print("The numbers: ")
for num in numbers:
print(num)
- 習(xí)題 34: 訪問列表的元素
# coding=utf-8
# 習(xí)題34:訪問列表的元素
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
x = len(animals)
print(x)
print(animals[0])
print(animals[5])
Week1 01 作業(yè)遺留的一些問題
- 其他格式符的嘗試使用
print("%s" % 42) # %s 轉(zhuǎn)化為字符串 輸出結(jié)果:42
print("%d" % 42) # %d 轉(zhuǎn)化為十進(jìn)制整數(shù) 輸出結(jié)果:42
print("%x" % 42) # %x 轉(zhuǎn)化為十六進(jìn)制整數(shù) 輸出結(jié)果:2a
print("%o" % 42) # %o 轉(zhuǎn)化為八進(jìn)制整數(shù) 輸出結(jié)果:52
print("%f" % 42) # %f 轉(zhuǎn)化為十進(jìn)制浮點(diǎn)數(shù) 輸出結(jié)果:42.000000
print("%e" % 42) # %e 轉(zhuǎn)化為以科學(xué)計(jì)數(shù)法表示的浮點(diǎn)數(shù) 輸出結(jié)果:4.200000e+01
print("%g" % 4236774665656.0364646) # %g 根據(jù)值的大小決定使用%f或者%e,以十進(jìn)制或科學(xué)計(jì)數(shù)法表示的浮點(diǎn)數(shù) 4.23677e+12
print("%d%%" % 100) # %% 文本值 % 本身
print("%r" % '1%')
# 試著使用變量將英寸和磅轉(zhuǎn)換成厘米和千克。不要直接鍵入答案。使用 Python 的計(jì)算功能來完成。
my_height_1 = 66.54 # inches
my_weight_1 = 136.69 # pounds
print("I'm %s inches tall, which means I'm %d centimeters tall." % (my_height_1, my_height_1 * 2.54))
print("I'm %s pounds heavy, which means I'm %d kilograms heavy." % (my_weight_1, my_weight_1 * 0.45359))
- 習(xí)題10:轉(zhuǎn)義字符
# 意義:告訴Python不要弄錯,要正確的區(qū)分字符串里非打印字符和打印字符。
print("\n")
print("I am 6'2\" tall.") # 將字符串中的雙引號轉(zhuǎn)義
print('I am 6\'2" tall.') # 將字符串中的單引號轉(zhuǎn)義
- 習(xí)題10 加分習(xí)題
# 10.3 將轉(zhuǎn)義序列和格式化字符串放到一起,創(chuàng)建一種更復(fù)雜的格式
print("\n")
print("I'm %r tall.\nI'm %s pouds heavy." % ('6\'22"', my_weight_1))
print("I'm %s tall.\nI'm %s pouds heavy." % ('6\'22"', my_weight_1))
# 記得 %r 格式化字符串嗎?使用 %r 搭配單引號和雙引號轉(zhuǎn)義字符打印一些字符串出來。 將 %r 和 %s 比較一下。
注意到了嗎?%r 打印出來的是你寫在腳本里的內(nèi)容,而 %s 打印的是你應(yīng)該看到的內(nèi)容。
%r 的含義是“不管什么都打印出來”,而 %s 是先解析、轉(zhuǎn)化成字符串再打印的。
- 其他的轉(zhuǎn)義字符
print("AA\nAA") # 換行
print("AA\tAA\tAA") # 縮進(jìn),又叫橫向制表符
print("AA\bAA") # 退一個字符 輸出結(jié)果 AAA
print("AA\vAA\vAA") # 縱向制表符,暫時沒有琢磨出來和\t 有什么不一樣的
print("\nAA\rAA") # 回車符,也沒有琢磨出來有什么用,暫時了解下吧。