【python】入门学习(四)

函数:

定义函数

#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']

 

转载于:https://www.cnblogs.com/dplearning/p/3951490.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值