鱼C论坛

 找回密码
 立即注册
查看: 2455|回复: 0

[学习笔记] python复盘:018函数:灵活即强大

[复制链接]
发表于 2020-2-12 11:28:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 慕良 于 2020-2-12 11:32 编辑

018函数:灵活即强大

一、形参parameter和实参argument
1、形参:函数定义过程中()里的参数
2、实参:函数调用过程中传递进去的参数
  1. >>> def First(name):
  2.         '函数定义过程中的name是形参'
  3.         #因为他只是一个形式,表示占据一个参数位置
  4.         print ("输入的" + name + '是实参,因为他是具体的参数值。')
  5. >>> First.__doc__
  6. '函数定义过程中的name是形参'
  7. >>> First('xx')
  8. 输入的xx是实参,因为他是具体的参数值。
复制代码


二、函数文档:为方便他人理解
  1. >>> First.__doc__
  2. '函数定义过程中的name是形参'
  3. >>> help(First)
  4. Help on function First in module __main__:

  5. First(name)
  6.     函数定义过程中的name是形参

  7. >>> print.__doc__
  8. "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile:  a file-like object (stream); defaults to the current sys.stdout.\nsep:   string inserted between values, default a space.\nend:   string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
  9. >>> help(print)
  10. Help on built-in function print in module builtins:

  11. print(...)
  12.     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  13.    
  14.     Prints the values to a stream, or to sys.stdout by default.
  15.     Optional keyword arguments:
  16.     file:  a file-like object (stream); defaults to the current sys.stdout.
  17.     sep:   string inserted between values, default a space.
  18.     end:   string appended after the last value, default a newline.
  19.     flush: whether to forcibly flush the stream.
复制代码


三、关键字参数
  1. >>> def say(name,words):
  2.         print(name + '->' + words)

  3.        
  4. >>> say('xx','666')
  5. xx->666
  6. >>> say('666','xx')
  7. 666->xx
  8. >>> say(words = '666',name = 'xx')
  9. xx->666
复制代码


四、默认参数
  1. >>> def say(name = 'xx',words = '888'):
  2.         print(name + '->' + words)

  3.        
  4. >>> say()
  5. xx->888
  6. >>> say('yy')
  7. yy->888
  8. >>> say('yy','555')
  9. yy->555
复制代码


五、收集参数(可变参数)
  1. >>> def test(*params):
  2.         print('参数的长度是:',len(params));
  3.         print('第二个参数是:',params[1]);
  4. >>> test(4,'xx',3.14,8,6,10)
  5. 参数的长度是: 6
  6. 第二个参数是: xx
  7. >>> def test(*params,exp):
  8.         print('参数的长度是:',len(params),exp);
  9.         print('第二个参数是:',params[1]);
  10. >>> test(4,'xx',3.14,8,6,exp=10)
  11. 参数的长度是: 5 10
  12. 第二个参数是: xx
  13. >>> def test(*params,exp=10):
  14.         print('参数的长度是:',len(params),exp);
  15.         print('第二个参数是:',params[1]);
  16. >>> test(4,'xx',3.14,8,6,10)
  17. 参数的长度是: 6 10
  18. 第二个参数是: xx
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 15:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表