【Python爬虫】-第二周 习题 18-26

ex18

代码

#ex18命名、变量、代码、函数的练习

# this one is like your script with argv
def print_two(*args):
    arg1, arg2 = 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):
    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()

运行结果

"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex18.py"
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First'
I got nothin'.

Process finished with exit code 0

加分习题
为自己写一个函数注意事项以供后续参考。你可以写在一个索引卡片上随时阅读,直到你记住所有的要
点为止。注意事项如下:

  1. 函数定义是以 def 开始的吗?\是的,创建函数
  2. 函数名称是以字符和下划线 _ 组成的吗?\是的
  3. 函数名称是不是紧跟着括号 ( ? \是的
  4. 括号里是否包含参数?多个参数是否以逗号隔开?\可以
  5. 参数名称是否有重复?(不能使用重复的参数名)\不可以
  6. 紧跟着参数的是不是括号和冒号 ): ? \是的
  7. 紧跟着函数定义的代码是否使用了 4 个空格的缩进 (indent) ? \使用了
  8. 函数结束的位置是否取消了缩进 (“dedent”) ? \取消了
当你运行(或者说“使用 use” 或者“调用 call” )一个函数时,记得检查下面的要点:
  1. 调运函数时是否使用了函数的名称? \没有
  2. 函数名称是否紧跟着 ( ? \没有
  3. 括号后有无参数?多个参数是否以逗号隔开?\可以
  4. 函数是否以 ) 结尾?\是的

按照这两份检查表里的内容检查你的练习,直到你不需要检查表为止。
最后,将下面这句话阅读几遍:
“‘运行函数 (run)’ 、‘调用函数 (call)’ 、和 ‘使用函数 (use)’ 是同一个意思”

ex19

代码

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print("You have %d cheesee!" % cheese_count)
    print("You have %d boxes of crackers!" % boxes_of_crackers)
    print("Man that's enough for a party!")#男人足够参加聚会了!
    print("Get a blanket.\n")#拿条毯子

print("We can just give the funcation numbers directly:")#我们可以直接使用这些功能
cheese_and_crackers(20, 30)

print("Or, we can 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_cheese + 100, amount_of_crackers + 1000)

运行结果

"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex19.py"
We can just give the funcation numbers directly:
You have 20 cheesee!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

Or, we can use variables from our script:
You have 10 cheesee!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheesee!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheesee!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.


Process finished with exit code 0

加分习题

  1. 倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。
  2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。

ex20

#ex20 函数和文件

from sys import argv

script, input_file = argv

def print_all(f):
    print(f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print(line_count, f.readline())

current_file = open(input_file)

print("First let's print the whole file:\n")#首先让我们打印整个文件

print_all(current_file)

print("Now let't rewind, kind of like a tape.")#现在让我们倒带,像磁带

rewind(current_file)

print("Let's print three lines:")#让我们打印3行

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

代码运行

"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex20.py" test.txt
First let's print the whole file:

随便填写点东西测试下,

人生如雪,我学python!
Now let't rewind, kind of like a tape.
Let's print three lines:
1 随便填写点东西测试下,

2 

3 人生如雪,我学python!

Process finished with exit code 0

因为我的test的文件和练习中的不同,所以代码运行的结果也不一样。

ex21

代码

#ex21 函数可以返回东西

def add(a, b):#加
    print("ADDING %d + %d" % (a, b))
    return a + b

def subtract(a, b):#减去
    print("SUBTRACT %d - %d" % (a, b))
    return a - b

def multiply(a, b):
    print("MULTIPLY %d * %d" % (a, b))
    return a * b

def divide(a,b):
    print("DIVID %d / %d" % (a,b))
    return a / b

print("Let's do some math with just functions!")

age = add(30, 5)
height = subtract(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, subtract(height, multiply(weight, divide(iq, 2))))

print("That becomes:", what, "Can you do it by hand?")#那就是:“什么,”你能用手做吗?

代码运算

"C:\Program Files\Python36\python.exe" "E:/学习/xiangmu/week two/ex21.py"
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACT 78 - 4
MULTIPLY 90 * 2
DIVID 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVID 50 / 2
MULTIPLY 180 * 25
SUBTRACT 74 - 4500
ADDING 35 + -4426
That becomes: -4391.0 Can you do it by hand?

Process finished with exit code 0

常见 问题回 答
为什么 Python 会把函数或公式倒着打印出来?
其实不是倒着打印,而是自内而外打印。如果你把函数内容逐句看下去,你会发现这里的规律。试
着搞清楚为什么说它是“自内而外”而不是“自下而上”。
怎样使用 raw_input() 输入自定义值?
记得 int(raw_input()) 吧?不过这样也有一个问题,那就是你无法输入浮点数,所以你可
以试着使用 float(raw_input()) 。
你说的“写一个公式”是什么意思?
来个简单的例子吧: 24 + 34 / 100 - 1023 —— 把它用函数的形式写出来。然后自己想
一些数学式子,像公式一样用变量写出来。

ex22

平时的积累

看见这道题目,好亲切,平时每个章节的练习,出了敲代码,我都有做纸质笔记,记录了很多符号的用途和单词的释义。

ex23

读代码的确蛮重要的,会去尝试读读另一本入门时的代码《简明python教程》和菜鸟网站的python教程。

ex24

#习题 24: 更多练习

print("Let's  practice everyting.")
print("You\'d need to know\ 'bout escapes with \\ that do \n newlines and \t tabs.")#你要知道\ '布特越狱\\\\做\\n换行和制表符

poem = """
\tThe lovely world
 with logic so firmly planted
 cannot discern \n the need of love
 nor comperhend passion form intuition
 and requires an an explanation
 \n\t\twhere there is none.
"""
#可爱的世界 逻辑坚定 无法辨别爱的需要  也不是凭直觉理解激情  需要解释  \n\n T \那里有没有

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)#有一个起始点:%d
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))

运行结果

"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex23.py"
Let's  practice everyting.
You'd need to know\ 'bout escapes with \ that do 
 newlines and    tabs.
-------------

    The lovely world
 with logic so firmly planted
 cannot discern 
 the need of love
 nor comperhend passion form intuition
 and requires an an explanation
 
        where there is none.

-------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.

Process finished with exit code 0

加分习题

  1. 记得仔细检查结果,从后往前倒着检查,把代码朗读出来,在不清楚的位置加上注释。
  2. 故意把代码改错,运行并检查会发生什么样的错误,并且确认你有能力改正这些错误。

ex25

代码

def break_words(stuff):
    """This function is 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 poping it off."""#打印出第一个词后弹出
    word = words.pop(0)
    print(word)

def print_last_word(words):
    """Prints the last word after poping 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 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)

CMD运行图

ex26

修改后的代码

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.poop(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 god\tthings come to those who weight."

words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print (sorted_words)

print_irst_and_last(sentence)

print_first_a_last_sorted(senence)

运行结果

"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex26.py"
Traceback (most recent call last):
  File "D:/小克学习/python/项目/week two/ex26.py", line 79, in <module>
    words = ex25.break_words(sentence)
NameError: name 'ex25' is not defined
Let's practice everything.
You'd need to know 'bout escapes with \ that do 
 newlines and    tabs.
--------------

    The lovely world
with logic so firmly planted
cannot discern 
 the needs of love
nor comprehend passion from intuition
and requires an explantion

        where there is none.

--------------
This should be five: 6
With a starting point of: 10000
We'd have 5000000 jeans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crabapples.

Process finished with exit code 1

总结:

Traceback (most recent call last):
File "D:/小克学习/python/项目/week two/ex26.py", line 79, in <module>
words = ex25.break_words(sentence)
NameError: name 'ex25' is not defined

这个要import ex25了, 没有进行下去,其他的东西都修改过来了。

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

推荐阅读更多精彩内容