python学习之函数和函数参数
2024-08-28 00:31:05
#方法的参数定义和默认参数的定义
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
print("true");
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise OSError('uncooperative user');#相当于c#中的throw;
print(complaint) #方法的调用
def show():
ask_ok("please input docstring"); #默认值的共享
def fun(n,args=[]):
args.append(n);
return args; print(fun(2));
print(fun(3));#长度加1
print(fun(4));#长度加1 #除去默认值的累计,->为注释,表示方法的返回值类型
def func(n,args=None)->[]:
if args is None:
args=[];
args.append(n);
return args; print(func(2));
print(func(3));#长度1
print(func(4));#长度1 #*当最后一个形参以 **name 形式出现,它接收一个字典 (见映射类型 —— 字典) ,该字典包含了所有未出现在形式参数列表中的关键字参数。
#它还可能与 *name 形式的参数(在下一小节中所述)组合使用,*name 接收一个包含所有没有出现在形式参数列表中的位置参数元组。
#(*name 必须出现在 ** name 之前。)例如,如果我们定义这样的函数: def getInfo(info,*argument,**keywords):
print("this is ",info);
for msg in argument:
print(msg);
for kw in keywords:
print(kw,":",keywords[kw]); getInfo("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch"); #参数的分拆
def parrot(name="xiaoxiao",age=24):
print("my name is",name,end='');
print("and my age is ",age,end=''); student={"name":"jack","age":25};
parrot(**student); stu=["jack",25];
parrot(*stu); #pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
#pairs.sort(key=lambda pair: pair[1]) #lamda表达式的使用,就是逆名函数
def sorter(L=None):
if L is None:
L=[];
L.sort(key=lambda pair:pair[1]);
return L; L = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')];
print(sorter(L)); #文档字符串
def myfunction():
"""Do nothing,,,but
No,really,,,it doesn't
""";
pass; print(myfunction.__doc__);
最新文章
- `UnityEditor.EditorUtility&#39; does not contain a definition for `GetMiniThumbnail&#39;
- c++中有些重载运算符为什么要返回引用
- 最短路径dijkstra算法
- MongoDB查询并更新一粟
- jquery判断checkbox是否选中及改变checkbox状态[转]
- 创建App IDs时选择App ID Prefix才能勾选push notifications
- Mac Outlook数据文件的位置
- UVALive 2523	Machine Schedule(二分图求最大匹配数)
- 通过实例介绍持续集成的应用--基于Jenkins
- 阿里云下Linux服务器安装Mysql、mongodb
- JS实现定时任务,每隔N秒请求后台——setInterval定时和ajax请求
- LeetCode(86):分隔链表
- T-SQL:基础练习(杂)
- 《Inside C#》笔记(十三) 多线程 下
- ccf题库中2016年4月2日俄罗斯方块问题
- poj 1797 最大最小路段【dijkstra】 (经典)
- ubantu 安装mysql 5.7 解决安装不提示设置密码问题
- sqlserver 数据分发复制 发布订阅
- idea使用git提交代码到远程,这里是没有冲突的演示
- 升级优化关于日志生成logging封装TimedRotatingFileHandler