笨方法学python-7(习题18-22)

习题18:命名、变量、代码、函数

def print_two(*args):
    arg1, arg2 = args
    print("arg1: %r, arg2: %r" % (arg1, arg2))

def print_two_again(arg1, arg2):
    print("arg1: %r, arg2: %r" % (arg1, arg2))

def print_one(arg1):
    print("arg1: %r" % arg1)

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 个空格的缩进 ( indent )

8. 函数结束的位置取消了缩进 (“dedent”)

当你运行(或者说“使用 use”或者“调用 call”)一个函数时,记得检查下面的要点:

1. 调运函数时是否使用了函数的名称?

2. 函数名称是否紧跟着  ( ?

3. 括号后有无参数?多个参数是否以逗号隔开?

4. 函数是否以  ) 结尾?

按照这两份检查表里的内容检查你的练习,直到你不需要检查表为止。

最后,将下面这句话阅读几遍:

“‘运行函数(run)’、‘调用函数(call)’、和 ‘使用函数(use)’是同一个意思”



习题19:函数和变量

def cheese_and_crackers(cheese_count,boxes_of_crackers):
    print("You have %d cheese!" % 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 function 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, variable and math:")
cheese_and_crackers(amount_of_cheese+100, amount_of_crackers+1000)


1.  倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。

2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。

3. 自己编至少一个函数出来,然后用 10 种方法运行这个函数。

随便写了一个,很简单

def add(a, b):
    print("The first number is: %d" % a)
    print("The other number is: %d" % b)
    print("Now I'm going to add the two number: %d" % (a+b))
print("My first try:")
add(10, 20)
print("Again:")
add(10-2, 20+3)
print("the third time:")
aa = 17
bb = 9
add(aa, bb)
print("Fourth time:")
add(aa+3, bb/3)



习题20:函数和文件

from sys import argv
script, input_file = argv
def print_all(f):
    print(f.read())   # 让f执行read函数,读取文件并打印
def rewind(f):  # 定义函数rewind(重置指针到文件开头位置)
    f.seek(0)   # 让f执行seek函数,将读写位置移动到文件开头
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'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
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)



1.  通读脚本,在每行之前加上注解,以理解脚本里发生的事情。

2. 每次 print_a_line 运行时,你都传递了一个叫  current_line 的变量。在每次调用函数时,打印出  current_line 的至,跟踪一下它在 print_a_line 中是怎样变成  line_count 的。

readline会扫描文件的字节,直到找到下一个\n,停止扫描,下一次从此停止位置继续扫描。相当于一次扫描输出一行。

line_count我把它理解为是计数器,它正好和被调用的位置一样。

引用CSDN上一位大神的解释:

这里其实line_count要叫做位置参数,之所以调用时的参数current_line成为了函数定义时的line_count就是因为它们在定义与被调用时所处的位置是一样的。 
如果我们把函数定义时两个参数的位置对调,并保持调用的顺序不变。或者,函数定义时不变,调用时对调。都会因为行号这个整数(int)没有readline()这个方法而导致错误发生。

3. 找出脚本中每一个用到函数的地方。检查  def 一行,确认参数没有用错。

4. 上网研究一下  file 中的  seek 函数是做什么用的。试着运行  pydoc file 看看能不能学到更多。

看代码注释,seek函数将读写位置移动到文件的开头。其处理的是字节而非行。

5. 研究一下  += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。

赋值运算符。


习题21:函数可以返回东西

def add(a, b):
    print("ADDING %d +%d" % (a, b))
    return a + b
def subtract(a, b):
    print("SUBTRACTING %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 funtions!")
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))
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?")



1.  如果你不是很确定  return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在  = 右边的东西作为一个函数的返回值。

2. 这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。

weight=height-((iq/2)*weight)+age分开写

3. 一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。

4. 最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。

def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
def multiply(a, b):
    return a * b
def divide(a, b):
    return a / b
print("Let's do some math with just funtions!")
# 20-8/4+2*3
what = add(subtract(20, divide(8, 4)), multiply(2, 3))
print("That becomes:", what, "Can you do it by hand?")




习题22:到现在你学到了那些东西?

简单整理一下

print

#

"""

+    -     *     /    %    <    >    <=    >=

变量

%d

%s

%r

\n

\t

input

from sys import argv

open

read

readline

close

write(stuff)

seek(0)回到文件开头

truncate清空文件

from os.path import exists

def

return





猜你喜欢

转载自blog.csdn.net/jesmine_gu/article/details/80913062
今日推荐