Python 函数相关

来源:互联网 发布:fm球员在线数据库 编辑:程序博客网 时间:2024/05/29 17:29

定义函数

def functionname(params):  #注意冒号不要忘记    statement1             #注意缩进    statement2

一个列子:

这里需要提的是一定要注意Python的格式。c++就是非常随意,怎么写都行,在Python时要注意。。。

注意:

python和C++/Java不一样,没有主函数一说,也就是说python语句执行不是从所谓的主函数main开始的。
当运行单个python文件时,如运行a.py,这个时候a的一个属性namemain
当调用某个python文件时,如b.py调用a.py,这个时候a的属性name是模块名a。

详细可参考:http://blog.csdn.net/perfumekristy/article/details/8805984

def palindrome(s):                #判断回文的函数    return s == s[::-1]if __name__ == '__main__':            s = input("Enter a string: ")    if palindrome(s):        print("Yay a palindrome")    else:        print("Oh no, not a palindrome")

局部变量和全局变量

因为在Python中不需要声明变量,因此这点在全局变量与c++中不同。

#!/usr/bin/env python3def change():    a = 90             #这里是内部变量,如果在c中,则为全局的a值    print(a)           #如果要其全局则 globle aa = 9print("Before the function call ", a)print("inside change function", end=' ')change()print("After the function call ", a)

默认参数

和c++类似,可以在参数列表中定义默认参数

#如果def(12)也可调用,这样b=-99#需要注意f(a,b=90,c)是错误的>>> def test(a , b=-99):...     if a > b:...         return True...     else:...         return False

文档字符串

个人认为这是非常牛的功能,使用文档字符串(docstrings)来说明如何使用代码,这在交互模式非常有用。

>>> def hello(*, name='User'):...     print("Hello", name)...>>> hello('shiyanlou')Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: hello() takes 0 positional arguments but 1 was given>>> hello(name='shiyanlou')Hello Kushal了解更多,请阅读PEP-31026. 文档字符串在 Python 里我们使用文档字符串(docstrings)来说明如何使用代码,这在交互模式非常有用,也能用于自动创建文档。下面我们来看看使用文档字符串的例子。#!/usr/bin/env python3import math             #导入模块#注意形式def longest_side(a, b):             """               Function to find the length of the longest side of a right triangle.    :arg a: Side a of the triangle    :arg b: Side b of the triangle    :return: Length of the longest side c as float    """    return math.sqrt(a*a + b*b)if __name__ == '__main__':    print(longest_side.__doc__)     #调用    print(longest_side(4,5))        #调用

高阶函数

map函数

它接受一个函数和一个序列(迭代器)作为输入,然后对序列(迭代器)的每一个值应用这个函数,返回一个序列(迭代器),其包含应用函数后的结果。

>>> lst = [1, 2, 3, 4, 5]>>> def square(num):...     "返回所给数字的平方."...     return num * num...>>> print(list(map(square, lst)))   #仔细理解,优雅[1, 4, 9, 16, 25]

参考:https://www.shiyanlou.com/courses/running

0 0
原创粉丝点击