【Python爬虫】-【第一周】02-作业

  1. 习题27:记住逻辑关系
    *心得:
    ①理解会比强记更牢靠;
    ②后面的比较复杂的布尔运算其实就是 与或非 + 4个等于判定 + 真假值 的组合,所以真值表一定要非常熟悉;
    ③网上找到的一个速记口诀:真真得真(与运算),假假得假(或运算),同假异真(异或运算)。
  1. 习题28:布尔表达式练习
# -- cdoing:utf-8 --
# 习题 28:布尔表达式练习
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

*心得:
①在运算之前应该先浏览一遍整个运算式子,再按照真值表中的基本运算单元去拆解求真值;
②《笨办法学Python》没有强调的是括号的优先级:如果有括号,优先进行括号内的布尔表达式。如果括号内有多个层级的括号,应该由内向外进行计算。可参考数学计算的多层级括号计算次序。== 、!= 判断的运算,等号两边也是可能包含括号的,比如 (3 == 2 and 6 != 7) == (6 > 7 or 6 >3),not( )、( ) and/or ( )都应该先从括号内的运算开始。

加分习题:
27.1 Python 里还有很多和 != 、 == 类似的操作符. 试着尽可能多地列出 Python 中的等价运算符。例如 < 或者 <= 就是。

print(7 < 8) # True
print(7 <= 7) # True
print(7 > 8) # False
print(7 >= 7) # True
print(7 != 7) # False
  1. 习题29:如果if
# --coding:utf-8 --
# 习题 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.")

加分习题:
29.1 你认为 if 对于它下一行的代码做了什么?
if给下一行提供了执行与否的判定,如果if False,下一行语句不执行(跳过)
29.2、29.3 为什么 if 语句的下一行需要 4 个空格的缩进?如果不缩进,会发生什么事情?
下一行执行的前提是if True,缩进的代码会在if True的条件下执行。如果不缩进,代码运行会报错。(总觉得《笨办法学Python》的答案是回答“为什么if条件句后要有个冒号”这个问题的。我觉得if条件句、while-loop和for-loop中关于代码缩进和不缩进,缩进多少,是个很值得注意和探究的问题,很多时候循环中差一个缩进就会得到完全不同的结果了。)
29.4 把习题 27 中的其它布尔表达式放到if 语句中会不会也可以运行呢?
if False/if True 会根据if 后面的逻辑表达式的最终结果进行判断。

  1. Else 和 If
# -- coding:utf-8 --
# 习题 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.")

加分习题:
30.1 猜想一下 elif 和 else 的功能
if-else 语句块类似于简单的if 语句,但其中的else 语句让你能够指定条件测试未通过时要执行的操作。
if-elif-else结构,python只执行if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,python将执行紧跟在它后面的代码,并跳过余下的测试。

30.3 试着写一些复杂的布尔表达式,例如 cars > people and buses < cars。

if cars > people and buses < cars:
      print("We should take the cars.")
  1. 作出决定
# -- coding:utf-8 --
# 习题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!")

心得:
嵌套时候的缩进太重要了。准确的缩进能够准确的传达层次,代码的易读性也比较高。

  1. 循环和列表
# -- coding:utf-8 --
# 习题 32:循环和列表 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 = [] # 创建空列表
# 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) 

加分习题:
32.1 注意一下 range 的用法。查一下 range 函数并理解它。
range()可以生成一系列的数字,函数range()包含两个参数,让python从指定的第一个值开始数,并在到达指定的第二个值后停止,因此输出不包含第二个值。
32.2 在第 22 行,你可以可以直接将 elements 赋值为range(0,6),而无需使用 for 循环?

elements_1 = list(range(1,3))

32.3 在 Python 文档中找到关于列表的内容,仔细阅读以下,除了 append 以外列表还支持哪些操作?

①修改:hairs[0] = 'green'
②永久删除指定索引元素:del hairs[0]
③删除(弹出)最后一个元素:color_1 = hairs.pop()
④删除指定值(列表中的第一个):hairs.remove('blue')
⑤对列表进行永久性排序:hairs.sort()
⑥对列表进行临时排序:hairs_sorted = sorted(hairs)

  1. While 循环
# coding=utf-8
# 习题33:while循环 while-loop
# while循环会一直执行它下面的代码片段,直到它对应的布尔表达式为False时才会停下来 
i = 0
numbers = []
while i < 6:
      print("At the top i is %d" % i)
      numbers.append(i)
      i += 1 # 递增,有结束while循环的条件
      print("Numbers now: ", numbers)
      print("At the bottom i is %d" % i)
print("The numbers: ")
for num in numbers:
      print(num)

加分习题
33.1 /33.2/33.3将这个 while 循环改成一个函数,将测试条件(i < 6)中的 6 换成一个变量。

i = 0
end_num = 9
step_num = 2 # 设置步长为2
numbers = []
while i < end_num:
      print("At the top i is %d" % i)
      numbers.append(i)
      i += step_num # 递增,有结束while循环的条件
      print("Numbers now: ", numbers)
      print("At the bottom i is %d" % i)
print("The numbers: ")
for num in numbers:
      print(num)
  1. 习题 34: 访问列表的元素
# coding=utf-8
# 习题34:访问列表的元素
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
x = len(animals)
print(x)
print(animals[0])
print(animals[5])

Week1 01 作业遗留的一些问题

  • 其他格式符的尝试使用
print("%s" % 42) # %s 转化为字符串 输出结果:42
print("%d" % 42) # %d 转化为十进制整数 输出结果:42
print("%x" % 42) # %x 转化为十六进制整数 输出结果:2a
print("%o" % 42) # %o 转化为八进制整数 输出结果:52
print("%f" % 42) # %f 转化为十进制浮点数 输出结果:42.000000
print("%e" % 42) # %e 转化为以科学计数法表示的浮点数 输出结果:4.200000e+01
print("%g" % 4236774665656.0364646) # %g 根据值的大小决定使用%f或者%e,以十进制或科学计数法表示的浮点数 4.23677e+12
print("%d%%" % 100) # %% 文本值 % 本身
print("%r" % '1%')
# 试着使用变量将英寸和磅转换成厘米和千克。不要直接键入答案。使用 Python 的计算功能来完成。
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))
  • 习题10:转义字符
# 意义:告诉Python不要弄错,要正确的区分字符串里非打印字符和打印字符。
print("\n")
print("I am 6'2\" tall.") # 将字符串中的双引号转义
print('I am 6\'2" tall.') # 将字符串中的单引号转义
  • 习题10 加分习题
# 10.3 将转义序列和格式化字符串放到一起,创建一种更复杂的格式
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 搭配单引号和双引号转义字符打印一些字符串出来。 将 %r 和 %s 比较一下。
注意到了吗?%r 打印出来的是你写在脚本里的内容,而 %s 打印的是你应该看到的内容。
%r 的含义是“不管什么都打印出来”,而 %s 是先解析、转化成字符串再打印的。
  • 其他的转义字符
print("AA\nAA") # 换行
print("AA\tAA\tAA") # 缩进,又叫横向制表符
print("AA\bAA") # 退一个字符 输出结果 AAA
print("AA\vAA\vAA") # 纵向制表符,暂时没有琢磨出来和\t 有什么不一样的
print("\nAA\rAA") # 回车符,也没有琢磨出来有什么用,暂时了解下吧。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容