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

  1. 习题18 命名、变量、代码、函数
# this one is like your scripts with argv
def print_two(*args):
      arg1, arg2 = args # 将参数解包,args意味着参数不固定 根据传递的参数去判断参数
      print("arg1: %r, arg2: %r" % (arg1, arg2)) # 打印解包后的参数
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2): # 传递两个参数,def print_two(*args): +   arg1, arg2 = args 作用一样,合并了指定参数和参数解包的过程
      print("arg1: %r, arg2: %r" % (arg1, arg2))
# this just takes one argument
def print_one(arg1): # 定义一个函数,只接受一个变量并打印
      print("arg1: %r" % arg1)
# this one takes no arguments
def print_none(): # 定义一个函数,不接受变量传递,值打印一段文本。
      print("I got nothin.")
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()

加分习题:
函数定义注意事项:
1.函数定义以def开始;
2.函数名称以字符和下划线_组成(小写字符,一般默认大写字符为类);
3.函数名称紧接着括号,括号里包含需要传递实参的形参名及形参个数;
4.括号里参数可以为空,也可以多个参数,参数之间用逗号隔开;
5.参数名称不能重复;
6.紧接着参数的是右括号和冒号):
7.紧跟着函数定义的代码使用了4个空格的缩进,表示这段代码包含在函数定义代码块中;

8.函数结束的位置/下一个代码段的开始,取消缩进。
函数调用注意事项:
1.使用函数名称调用函数;
2.函数名称后紧跟着括号;
3.根据函数定义,传递与定义中个数相符、顺序相符的实参,多个参数之间以逗号隔开;
4.函数调用以)结果表示传递参数结束;
5.被调用函数的名称需与被定义的函数名称完全一致。

  1. 习题19 函数和变量
# 定义一个函数cheese_and_crackers,包含两个参数,cheese_count和boxes_of_crackers。这个函数执行4个打印的任务。
def cheese_and_crackers(cheese_count, boxes_of_carckers):
      print("You have %d cheeses!" % cheese_count)
      print("You have %d boxes of crackers!" % boxes_of_carckers)
      print("Man that's enough for a party!")
      print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30) # 调用函数cheese_and_crackers函数,传递两个参数,cheese_count = 20, boxes_of_crackers = 30
# 另外一种方式给函数传递参数
print("Or, we cam use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6) # 在函数中做运算,运算的结果为最终传递给函数的实参
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_crackers + 100, amount_of_crackers + 1000) # 在函数中做运算

加分习题:
19.2 自己编至少一个函数出来,

# 指定一个数,输出从1到这个数(包含这个数)之间的所有数字
def f(n):
      current_number = 1
      while current_number <= n:
          print(current_number)
          current_number += 1
f(6) # 输出结果为 1 2 3 4 5 6
  1. 习题20 函数和文件
from sys import argv # 从sys模块调用argv函数
script, input_file = argv # 解包argv,需要传递脚本名称script和input_file的名称
# 读取f文件内容并打印
def print_all(f):
    print(f.read())
# 移动文件读取指针到文件开头
def rewind(f):
    f.seek(0) # seek() 方法用于移动文件读取指针到指定位置。
# 每次读一行,并计数
def print_a_line(line_count, f):
    print(line_count, f.readline()) # readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字
current_file = open(input_file) # 打开文件,并将对象存储于current_file变量
print("Frist let's print the whole file:\n")
print_all(current_file) # 打印输出文件所有内容
print("Now let's rewind, kind of like a tape.")
rewind(current_file) # 移动文件读取指针到文件开头,从头读取文件
print("Let's print three lines:")
# 读取文件第一行,并计数,输出行号与行内容
current_line = 1
print_a_line(current_line, current_file)
# 读取文件第二行,并计数,输出行号与行内容
current_line = current_line + 1 # 等同于current_line += 1
print_a_line(current_line, current_file)
#  读取文件第三行,并计数,输出行号与行内容
current_line = current_line + 1
print_a_line(current_line, current_file)

学习笔记:关于readline()函数的行读取方式

备注:readline()每运行一次,读取一行,print_a_line运行三次就会依次打印1,2,3行,而不是打印第一行三次。
current_line = 1
print_a_line(current_line, current_file) # 打印第一行
print_a_line(current_line, current_file) # 打印第二行
print_a_line(current_line, current_file) # 打印第三行
  1. 习题21 函数可以返回东西
def add(a, b): # 定义一个函数,这个函数有两个任务,打印一段文字,并将参数的和返回给函数
      print("ADDING %d + %d" % (a, b))
      return a + b
def substract(a, b):
      print("SUBSTRACTING %d - %d" % (a, b))
      return a - b
def multiply(a, b):
      print("MULTIPLYING %d * %d" % (a, b))
      return a * b
def divide(a, b):
      print("DIVIDING %d / %d" % (a, b))
      return a / b
print("Let's do some math with just functions!")
age = add(30, 5) # print(age) 输出值35.但是age = add(30,5)的结果为print("ADDING %d + %d" % (a, b))。
height = substract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, substract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
  1. 习题24 更多练习
print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do \nnewlines and \t tabs.') # 转义字符,正确打印
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of lovely
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
""" # \t换行符,\n缩进,''''''输出多行内容
print("-----------")
print(poem)
print("-----------")
five = 10 - 2 + 3 - 6 # 将数字运算的结果赋值给一个变量
print("This should be five: %s" % five)
# 定义一个函数,执行三个计算任务,并将结算结果值返回给函数
def secret_formula(started):
      jelly_beans = started * 500
      jars = jelly_beans / 1000
      crates = jars / 100
      return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point) # 同时传递三个参数
print("With a starting point of: %d" % start_point)
print("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))
start_point = start_point / 10
print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
  1. 习题25 更多更多练习
import ex25 as p # 将文件夹中的ex25.py导入到此程序中,且命名为p
sentence = "All good things come to those who wait."
words = p.break_words(sentence) # 句点法调用ex25中的函数
print(words)
sorted_words = p.sort_words(words)
print(sorted_words)
p.print_first_word(words)
p.print_last_word(words)
# print(wrods) # name 'wrods' is not defined
print(words)
p.print_first_word(sorted_words)
p.print_last_word(sorted_words)
print(sorted_words)
sorted_words = p.sort_sentence(sentence)
print(sorted_words)
p.print_first_and_last(sentence)
p.print_first_and_last_sorted(sentence)

学习笔记:关注模组和函数的导入
《笨办法学Pyhton》中是在先运行ex25.py,然后再python编译器里进行的交互练习。
我的代码里是在ex25.py的同一个目录下新建了一个py文件,然后
import ex25 as p将ex25导入到程序中,再使用句点法调用ex25.py中定义的函数。

  1. 习题26 考试(改错)
import ex25
def break_words(stuff):
    """This function will break up words for us."""
      words = stuff.split(' ')
      return words
def sort_words(words):
    """Sorts the words."""
      return sorted(words)
def print_first_word(words):
    """Prints the first word after popping it off."""
      word = words.pop(0)
      print(word)
def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print(word)
def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
      words = break_words(sentence)
      return sort_words(words)
def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
      words = break_words(sentence)
      print_first_word(words)
      print_last_word(words)
def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
      words = sort_sentence(sentence)
      print_first_word(words)
      print_last_word(words)
print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""
print("--------------")
print(poem)
print("--------------")
five = 10 - 2 + 3 - 5
print("This should be five: %s" % five)
def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates
start_point = 10000
'''
beans, jars, crates == secret_formula(start_point)
print("With a starting point of: %d" % start_point)
print("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))
'''
start_point = start_point / 10
print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))
sentence = "All good things come to those who wait."
words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)
print_first_word(words)
print_last_word(words)
ex25.print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print(sorted_words)
print_first_and_last(sentence)
print_first_and_last(sentence)

学习笔记:
**
代码常见语法错误
①函数定义def f()后缺少:
②print要讲打印的内容放在()内;
③除号是/而不是\;
④缩进错误;
与-的输入错误,另外函数名及参数名都只能是字母与数字以及的组合,并且不能以数字开头;
⑥使用了未定义的参数名、变量名;
⑦调用模组或模组中的函数需在代码前几行先导入;
⑧函数名、变量名输入错误。
**


心得体会:
新手学习python最容易犯的代码错误有两种,分别是语法错误逻辑错误
语法错误是指代码违背了代码语言的语法,例如括号不匹配、变量名称书写错误、使用了未定义的变量名等等,导致编译器进行语法检查时不通过。
逻辑错误是程序能运行,但是达不到预期结果。
语法错误很容易犯,很多细微的差别都可能使编译器报错。除了写代码时要细心之外,我们还要学会通过编译器的错误代码,发现错误并快速定位、改写语法错误的代码。

Paste_Image.png
Paste_Image.png

Pycharm、Sublime Txt等工具都自带语法高亮、错误提示,善用这些工具能够极大提高我们的效率,减少语法错误。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353

推荐阅读更多精彩内容