Python中的函数注意事项

来源:互联网 发布:mac谷歌翻墙教程 编辑:程序博客网 时间:2024/06/05 15:15

转自《笨方法学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 argvdef print_two(*args):arg1, arg2 = argsprint "arg1: %r, arg2: %r" % (arg1, arg2)# ok, that *args is actually pointless, we can just do thisdef print_two_again(arg1, arg2):print "arg1: %r, arg2: %r" % (arg1, arg2)# this just takes one argumentdef print_one(arg1):print "arg1: %r" % arg1# this one takes no argumentsdef print_none():print "I got nothin'."print_two("Zed", "Shaw")print_two_again("Zed", "Shaw")print_one("First!")print_none()


原创粉丝点击