Python中的函数注意事项

转自《笨方法学Python》。


函数注意事项:

1. 函数定义是以def开始的。

2. 函数名称是以字符和下划线组成的。

3. 函数名称后面紧跟括号。

4. 括号里可以包含参数,也可以不包含。如果包含多个参数,以逗号隔开。

5. 参数名称不能有重叠。

6. 紧跟着参数的是括号和冒号。

7. 紧跟着函数定义的代码使用4个空格的缩进。

8. 函数结束的位置取消缩进。


函数调用要点:

1. 调用函数时需使用函数的名称。

2. 函数名称紧跟括号。

3. 括号后的参数个数与函数定义中一致,多个参数以逗号隔开。

4. 以括号结尾。


例如:

# -- coding: utf-8 --

# 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()


猜你喜欢

转载自blog.csdn.net/SharonLu1216/article/details/77344396