码迷,mamicode.com
首页 > 编程语言 > 详细

【python】入门学习(四)

时间:2014-09-02 15:43:14      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   strong   ar   art   div   代码   

函数:

定义函数

#area.py

from math import pi
def area(radius):
    """Return the area of a circle with the given radius."""
    return pi * radius ** 2
>>> ================================ RESTART ================================
>>> 
>>> area(5.5)
95.03317777109125
>>> print(area.__doc__)
Return the area of a circle with the given radius.
>>> 

 

doctest #可用于自动运行文档字符串中的python示例代码

 

全局变量访问时一定要加上global

#error
name = Jack
def say_hello():
    print(Hello  + name + !)
def change_name(new_name):
    name = new_name
>>> say_hello()
Hello Jack!
>>> change_name(Mary)
>>> say_hello()
Hello Jack!
#correct
name = Jack
def say_hello():
    print(Hello  + name + !)
def change_name(new_name):
    global name
    name = new_name
>>> say_hello()
Hello Jack!
>>> change_name(Mary)
>>> say_hello()
Hello Mary!

 

main():被认为是程序的起点,可选不一定要。运行时必须输入main()

python中参数的传递都是按引用传参,python支持按值传参

在引用传参中,无法修改参数的值。下面的函数起作用:

#reference.py
def set1(x):
    x = 1
>>> ================================ RESTART ================================
>>> 
>>> y = 5
>>> set1(y)
>>> y
5

 

函数参数默认值:

注意:包含默认参数的形参一定要放在无默认参数的形参后面

        只有第一次调用函数时给默认参数赋值! #还不理解,先记下来

#greetings.py
def greet(name, greeting = Hello):
    print(greeting, name + !)
>>> greet(bob)
Hello bob!
>>> greet(bob, Good morning)
Good morning bob!

 

使用关键字传参,即在使用时也指明形参,可以不理会顺序,很好用:

#greetings.py
def greet(name = Bob, greeting = Hello):
    print(greeting, name + !)
>>> greet(greeting = Good evening, name = Mary)
Good evening Mary!
>>> greet(greeting = Good evening)
Good evening Bob!

也可以用模块化的方式来调用,模块中不包括main函数

>>> import greetings
>>> greetings.greet()
Hello Bob!
>>> dir(greetings)
[__builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__, __spec__, greet]

 

【python】入门学习(四)

标签:style   blog   color   使用   strong   ar   art   div   代码   

原文地址:http://www.cnblogs.com/dplearning/p/3951490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!