Python基础知识(四)

函数

函数可以做三样事情:

  • 它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
  • 它们可以接受参数,就跟你的脚本接受argv一样。
  • 通过使用#1 和 #2,它们可以让你创建“微型脚本”或者“小命令”。

python中你可以使用def新建函数。我将让你创建四个不同的函数,它们工作起来和你的脚本一样。然后我会演示给你各个函数之间的关系。

# this one is like your scripts 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()

让我们把地一个函数print_two分解一下,这个函数和你写脚本的方式差不多,因此你看上去应该会觉着比较眼熟:

  • 首先我们告诉Python创建一个函数,我们使用到的命令是def,也就是“定义(define)”的意思。

  • 紧接着def的是函数的名称。本例中它的名称是print_two,但名字可以随便取,就叫peanuts也没关系。但函数名最好能够体现出函数的功能来。

  • 然后我们告诉函数我们需要*args,这和脚本的argv非常相似,参数必须放在圆括号 () 中才能正常工作。

  • 接着我们用冒号:结束本行,然后开始下一行缩进。

  • 冒号以下,使用4个空格缩进的行都是属于print_two这个函数的内容。 其中第一行的作用是将参数解包,这和脚本参数解包的原理差不多。

  • 为了演示它的工作原理,我们把解包后的每个参数都打印出来。

函数print_two的问题是:它并不是创建函数最简单的方法。在 Python 函数中我们可以跳过整个参数解包的过程,直接使用()里边的名称作为变量名。这就是print_two_again实现的功能。

接下来的例子是print_one,它向你演示了函数如何接受单个参数。

最后一个例子是print_none,它向你演示了函数可以不接收任何参数。

常见问题

Q:什么字符允许用在函数名上?

和变量命名规则相同。不能以数字开头,并且只能包含字母数字和下划线。

Q:args 中的星号是干嘛的?

它告诉python把函数的所有参数组织一个列表放在args里。类似你之前用过的argv,只不过*args是用在函数里的。

函数和文件

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'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)

结果

$ python ex20.py test.txt
First let's print the whole file:

This is line 1
This is line 2
This is line 3

Now let's rewind, kind of like a tape.
Let's print three lines:
1 This is line 1

2 This is line 2

3 This is line 3

常见问题

Q:函数print_all中的f是什么?

f 就是一个变量,只不过这次它代表了一个文件。 Python中的文件就好像老旧的磁带驱动器,或者是像现在的DVD播放器。它有一个 “磁头”,你可以在文件中"查找"到这个磁头的位置,并且从那个位置开始运行。你每执行一次 f.seek(0),就靠近文件的开头一点。每执行一次f.readline()你就从文件中读取一行内容,并且把“磁头”移动到文件末尾,换行符\n的后面。

Q: 文件中为什么有3个空行?

函数 readline() 返回一行以\n结尾的文件内容, 在你调用print函数的最后增加一个逗号’,’,用来避免为每一行添加两个换行符\n。

Q:为什么seek(0)方法没有把current_line的值修改为0?

首先,seek()方法是按字节而不是按行为处理单元的。代码seek(0)重新定位在文件的第0位(第一个字节处)。再次,current_line是一个变量,在文件中没有真正的意义可言。我们是在手动的增加它的值。

Q:+=是什么?

你应该知道在英语里我们可以简写 “it is” 为 “it’s”,简写 “you are” 为 “you’re”。在英语里我们把这种写法称为缩写,同样的,+=是 =和 +两个操作符的缩写. 比如x = x + y可以缩写为x += y.

Q:readline()怎么知道每一行的分界在哪里?

readline()内部代码是扫描文件的每一个字节,直到找到一个\n字符代码,然后停止阅读,并返回到此之前获得的所有内容。代码中f的责任是在每次调用readline()之后,维护“磁头”在文件中的位置,以保证继续读后面的每一行。

函数的返回值

Python关键字return来将变量设置为“一个函数的值”。有一点你需要极其注意,不过我们先来编写下面的脚本吧:

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 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?")

现在我们创建了自己的加减乘除数学函数: add, subtract, multiply, 以及 divide。重要的是函数的最后一行,例如 add 的最后一行是 return a + b,它实现的功能是这样的:

  • 我们调用函数时使用了两个参数: a 和 b 。
  • 我们打印出这个函数的功能,这里就是计算加法(adding)
  • 接下来我们告诉 Python 让它做某个回传的动作:我们将 a + b 的值返回(return)。或者你可以这么说:“我将 a 和 b 加起来,再把结果返回。”
  • Python 将两个数字相加,然后当函数结束的时候,它就可以将 a + b 的结果赋予一个变量。

结果

$ python ex21.py
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes:  -4391 Can you do it by hand?

常见问题
Q:为什么Python打印公式或函数是反向的?

它们并不是真正的反向的, it’s “inside out.” When you start breaking down the function into separate formulas and function calls you’ll see how it works. Try to understand what I mean by “inside out” rather than “backward.”

Q: 怎样使用input() 输入我自己的值?

还记得 int(input())吗? 这样做有一个问题就是你不能输入浮点数,不过你可以使用 float(input())来输入。

Q: 你说的 "写一个公式"是什么意思?

试试先写24 + 34 / 100 - 1023,再用我们的函数转化一下。现在给你的数学公式加入变量,这样它就变成了一个公式。

猜你喜欢

转载自blog.csdn.net/weixin_43093289/article/details/83576373