4.1 控制结构

4.1.1 条件分支

  1. if ....:
  2. suite1
  3. elif ...:
  4. suite2
  5. ...
  6. elif ...:
  7. suiteN
  8. else:
  9. suite_else

条件表达式

  1. expression1 if boolean_expression else expression2
  1. import random
  2. 999 if random.random() > 0.5 else 0 #999 or 0
  1. 999 + 1 if random.random() > 0.5 else 0 # 1000 or 0
  2. 999 + (1 if random.random() > 0.5 else 0) # 1000 or 999

4.1.2 循环

4.1.2.1 while循环

  1. while boolean_expression:
  2. while_suite
  3. else: #有些时候还蛮有用的 循环正常执行结束后执行
  4. else_suite

4.1.2.2 for循环

  1. for expression in iterable:
  2. for_suite
  3. else: #循环正常结束后执行
  4. else_suite
  1. for i in range(5):
  2. print(i)
  3. else:
  4. print('!!!!')
  1. 0
  2. 1
  3. 2
  4. 3
  5. 4
  6. !!!!
  1. for i in range(5):
  2. if i == 3:
  3. break
  4. print(i)
  5. else:
  6. print('!!!!')
  1. 0
  2. 1
  3. 2

return 同样会跳过else_suite

4.2 异常处理

4.2.1 捕获与产生异常

  1. try:
  2. try_suite
  3. except exception_group1 as variable1:
  4. except_suite1
  5. ...
  6. except exception_group1 as variable1:
  7. except_suiteN
  8. else: #try部分正常执行才会执行这部分
  9. else_suite
  10. finally: #总会执行 即便异常没有被捕获到 往往用于确保资源被正确释放
  11. finally_suite

更加简单的try...finally...

  1. try:
  2. try_suite
  3. finally:
  4. finally_suite

产生异常 raise

  1. raise exception(args)
  2. raise exception(args) from original_exception
  3. raise
  1. raise KeyError('dasd') # KeyError: 'dasd'

4.2.2 自定义异常

  1. class exceptionName(baseException): pass

注意:上面的baseException是指某个已存在的关于异常的类

  1. class WAWAWAError(KeyError):
  2. pass

tips 用异常跳出深层嵌套循环

  1. flag = False
  2. for i in range(9):
  3. for j in range(9):
  4. for k in range(9):
  5. if i + j +k > 10:
  6. flag = True
  7. break
  8. if flag:
  9. break
  10. if flag:
  11. break
  12. else:
  13. print(flag)

当i + j + k > 10的时候,我们希望能跳出循环,虽然这个代码块的样子还挺帅的,但是很蠢吧。

  1. class ExitException(Exception): pass
  2. try:
  3. for i in range(9):
  4. for j in range(9):
  5. for k in range(9):
  6. if i + j +k > 10:
  7. raise ExitException()
  8. except ExitException:
  9. print('Come on!')
  10. else:
  11. print('You will not see me!')

4.3 自定义函数

Tips 参数默认值为可变时 危险

给定默认值的时候,参数时在程序执行def时就建立的了,所以,当参数默认值为可变对象的时候,危险。

  1. def append_if_even(x, lst=[]): #从对象绑定的角度考虑,合情合理
  2. if x % 2 == 0:
  3. lst.append(x)
  4. print(lst)
  5. append_if_even(2) #[2]
  6. append_if_even(2) #[2, 2]
  7. append_if_even(2) #[2, 2, 2]
  8. append_if_even(2) #[2, 2, 2, 2]

字符串 数字 元组等都是固定变量

  1. def append_if_even(x, lst=''):
  2. if x % 2 == 0:
  3. lst += '?'
  4. print(lst)
  5. append_if_even(2) # '?'
  6. append_if_even(2) # '?'
  7. append_if_even(2) # '?'
  8. append_if_even(2) # '?'
  1. def append_if_even(x, lst=None):
  2. lst = [] if lst is None else lst
  3. if x % 2 == 0:
  4. lst += '?'
  5. print(lst)

4.3.1 名称与Docstrings

  1. def simpledoc(real, dream='sky'):
  2. """ Returns the text I can not control now...
  3. real is any string; dream is the same as well, while it has default value 'sky'.
  4. Of course, your different people has various dreams, but we all need to confront
  5. the real life.
  6. >>> simpledoc('god')
  7. "haha happy"
  8. >>> simpledoc('god', 'earth')
  9. "don't cry, go forward..."
  10. """
  11. if real == 'god' and dream == 'sky':
  12. return 'haha happy'
  13. else:
  14. return "don't cry, go forward..."

4.3.2 参数与参数拆分

  1. def product(*args):
  2. print(args)
  3. result = 1
  4. for arg in args:
  5. result += arg
  6. return result
  7. product(2,3,4,5) # (2, 3, 4, 5) 15

*args 后面仍然可以使用关键词参数

  1. def sum_of_powers(*args, power=1): #虽然power不添加默认值不会报错,但是使用的时候必须用关键词参数的形式传入值
  2. result = 0
  3. for arg in args:
  4. result += arg ** power
  5. return result

* 用于区分位置参数和关键词参数 def f(a, b, *, c = 0): ...

  1. def sum_and_add(a, b, *, c = 0):
  2. return a + b + c
  3. sum_and_add(1, 2) # 3
  4. sum_and_add(1, 2, 1) #TypeError
  5. sum_and_add(1, 2, c = 1) # 4

f(**options)

**用于传入参数

  1. options = dict(a = 1, b = 2, c = 1) #如果有多余的参数,会TypeError
  2. sum_and_add(**options) # 4

**用于函数构建

  1. def add(prime = 0, **adds):
  2. for key, value in adds.items():
  3. print(key)
  4. prime += value
  5. return prime
  6. add(a = 1, b = 2, c = 3) # a b c 6

4.3.3 存取全局范围的变量 global

  1. def remain():
  2. global REMAIN
  3. REMAIN = 3
  4. def sum_and_add(a, b):
  5. remain() #得执行一次
  6. return a + b + REMAIN
  7. sum_and_add(1, 2) # 6

4.3.4 Lambda 函数

  1. lambda parameters: expression

expression 不能包含分支或循环,也不能包含return或yield。如果expression是一个元组,那么应该用括号包起来。

  1. f = lambda : (1, 2)
  2. f() # (1, 2)
  1. f = lambda x: "" if x == 1 else 's'
  2. f(1) # ''

4.3.5 断言 assert

  1. assert boolean_expression, optional_expression
  1. def product(*args):
  2. assert all(args), "0 argument"
  3. result = 1
  4. for arg in args:
  5. result *= arg
  6. return result
  7. product(*[1, 2, 3, 4]) # 24

练习


  1. import os
  2. import sys
  3. WORD_FORWARD = "Choose filename: "
  4. WORD_CONTINUE = "Press Enter to continue..."
  5. WORD_OPTION1 = "[A/a]dd [D/d]elete [S/s]ave [Q/q]uit [a]: "
  6. WORD_OPTION2 = "[A/a]dd [Q/q]uit [a]: "
  7. WORD_ERROR_FILENAME = "Sorry, {0} is not found..."
  8. WORD_ERROR_OPTION1 = "ERROR: invalid choice--enter one of 'AaDdSsQq'"
  9. WORD_ERROR_OPTION2 = "ERROR: invalid choice--enter one of 'AaQq'"
  10. WORD_FILES_ZERO = "-- no items are in list --"
  11. WORD_ADD_ITEM = "Add item: "
  12. WORD_DELETE_ITEM = "Delete item number (or 0 to cancel): "
  13. WORD_ERROR_DELETE = "The number exceeds the limits..."
  14. WORD_SAVE_ITEM = "Saved {0} item{1} to {2}"
  15. WORD_SAVE_UNSAVED = "Save unsaved changes (y/n) [y]: "
  16. def filename_and_set():
  17. f = None
  18. files = []
  19. global filename
  20. try:
  21. filename = input(WORD_FORWARD)
  22. if filename[-4:] != '.txt': #.txt 代替.lst
  23. filename += '.txt'
  24. f = open(filename)
  25. for item in f:
  26. files.append(item.rstrip())
  27. except FileNotFoundError:
  28. pass
  29. finally:
  30. if f is not None:
  31. f.close()
  32. return files
  33. def delete_item(files):
  34. flag = input(WORD_DELETE_ITEM)
  35. try:
  36. flag = int(flag)
  37. if flag is 0:
  38. pass
  39. else:
  40. files.pop(flag - 1)
  41. except ValueError:
  42. print("Integer is need...")
  43. except IndexError:
  44. print(WORD_ERROR_DELETE)
  45. def save_item(files):
  46. f = None
  47. n = len(files)
  48. try:
  49. f = open(filename, 'w', encoding='utf8')
  50. for item in files:
  51. f.write(item + '\n')
  52. print(WORD_SAVE_ITEM.format(n,
  53. 's' if n > 1 else '',
  54. filename))
  55. except:
  56. print('ERROR: SAVE...')
  57. finally:
  58. if f is not None:
  59. f.close()
  60. def quit_item(files):
  61. n = len(files)
  62. flag = input(WORD_SAVE_UNSAVED)
  63. if flag is 'y' or not flag:
  64. save_item(files)
  65. sys.exit()
  66. def option1(files, label):
  67. if label == 'A' or label == 'a' or not label:
  68. files.append(input(WORD_ADD_ITEM))
  69. elif label == 'D' or label == 'd':
  70. delete_item(files)
  71. elif label == 'S' or label =='s':
  72. save_item(files)
  73. elif label == 'Q' or label == 'q':
  74. quit_item(files)
  75. else:
  76. print(WORD_ERROR_OPTION1)
  77. def option2(files, label):
  78. if label == 'A' or label == 'a' or not label:
  79. files.append(input(WORD_ADD_ITEM))
  80. elif label == 'Q' or label == 'q':
  81. quit_item(files)
  82. else:
  83. print(WORD_ERROR_OPTION2)
  84. def screen_show(files):
  85. n = len(files)
  86. if n != 0:
  87. files.sort()
  88. if not n:
  89. print(WORD_FILES_ZERO)
  90. label = input(WORD_OPTION2)
  91. option2(files, label)
  92. else:
  93. for i in range(n):
  94. print("{0}: {1}".format(i+1, files[i]))
  95. label = input(WORD_OPTION1)
  96. option1(files, label)
  97. def main():
  98. files = filename_and_set()
  99. count = 1
  100. while True:
  101. count += 1
  102. if count > 10:
  103. break
  104. screen_show(files)
  105. print('\n\n')
  106. main()

Python Revisited Day 04 (控制结构与函数)的更多相关文章

  1. Python快速学习04:循环 & 函数

    前言 系列文章:[传送门] 也就今天认识了 LC ,很开心. 本文目录 循环 for while 中断 函数 函数定义 函数调用 for循环 Python 中的for 循环象shell 脚本里的for ...

  2. 翻译《Writing Idiomatic Python》(二):函数、异常

    原书参考:http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/ 上一篇:翻译<Writing Idiomatic ...

  3. PYTHON 100days学习笔记006:函数和模块的使用

    目录 Day006:函数和模块的使用 1.函数的作用 2.定义函数 2.1 语法 2.2 实例 2.3 函数的调用 4.函数的参数 4.1 必须参数 4.2 关键字参数 4.3 默认参数 4.4 不定 ...

  4. python应用 曲线拟合04

    python应用 曲线拟合04 → 多项式拟合 主要是使用 numpy 库中的 polyfit() 函数,见第 66 行, z = np.polyfit(x_proton, y, 3) ,其中待拟合曲 ...

  5. Python黑帽编程2.5 函数

    Python黑帽编程2.5 函数 写了几节的基础知识,真心感觉有点力不从心.这块的内容说实话,看文档是最好的方式,本人的写作水平,真的是找不出更好的写法,头疼.简单带过和没写一样,写详细了和本系列教程 ...

  6. Python学习【第九篇】函数

    函数 函数是什么? 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 在学习函数之前,一直遵循:面向过程编程,即:根据业务逻辑从上而下实现功能,其往往用一段代码来实现指定功能,开发过 ...

  7. Python标准库:内置函数hasattr(object, name)

    Python标准库:内置函数hasattr(object, name) 本函数是用来判断对象object的属性(name表示)是否存在.如果属性(name表示)存在,则返回True,否则返回False ...

  8. Python内置的字符串处理函数整理

    Python内置的字符串处理函数整理 作者: 字体:[增加 减小] 类型:转载 时间:2013-01-29我要评论 Python内置的字符串处理函数整理,收集常用的Python 内置的各种字符串处理 ...

  9. Python函数式编程:内置函数map()使用说明

    一.概述 map操作是函数式编程中的重要技术之一,其作用就是对一个集合中的每个元素做处理,生成一个新的元素,由这些新的元素组成一个新的集合的返回. 所以map操作后,产生的新集合的元素个数和原集合的元 ...

随机推荐

  1. Json.net日期格式化设置

    Json.net默认的时间格式化后带T,不符合一般的业务要求,重新设置JSON.NET的默认日期格式化方式,代码如下: /// <summary> /// Json.net默认转换设置 / ...

  2. adb入门学习笔记

    连接模拟器(模拟器桥接模式) 使用adb devices列出已连接到工作站的设备. 使用adb shell 启动设备或模拟器上的shell. 列出设备已安装的所有软件包 将电脑文件移动到手机模拟器上( ...

  3. ZooKeeper Observers解决节点过多时写性能下降问题

    ZooKeeper Observers Observers: Scaling ZooKeeper Without Hurting Write Performance How to use Observ ...

  4. WPF设计の不规则窗体

    我们在工作中,经常会需要画一些不规则的窗体,现在总结如下. 一.利用VisualBrush实现.这依赖于VisualBrush的特性,任何控件可以作为画刷,而画刷又可以作为背景. 此种方法可以用于实现 ...

  5. linux学习笔记整理(一)

    第二章  Linux基本操作 2.1 Linux网络相关概念和修改IP地址的方法2.2 关闭防火墙并设置开机开不启动2.3 临时和永久关闭Selinux2.4 设置系统光盘开机自动挂载2.5 配置本地 ...

  6. python六十四课——高阶函数练习题(三)

    案例五:求两个列表元素的和,返回新列表lt1 = [1,2,3,4]lt2 = [5,6]效果:[6,8,10,12] lt1=[1,2,3,4] lt2=[5,6] print(list(map(l ...

  7. JAVA序列化和反序列化XML

    package com.lss.utils; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.Bu ...

  8. idea在maven打包时运行Test测试, 导致打包失败, 乱七八糟的错误

    在maven打包时运行Test测试, 导致打包失败, 乱七八糟的错误 在maven projects中图标toggle'skip Tests' Mode //宏杰帮助 网上案例:https://blo ...

  9. Jmeter插件安装及使用

    1 安装Plugins Manager插件 1.1 下载Plugins Manager插件 插件下载官方地址:https://jmeter-plugins.org/downloads/all/ 将下载 ...

  10. [matlab] 7.快速搜索随机树(RRT---Rapidly-exploring Random Trees) 路径规划

    RRT是一种多维空间中有效率的规划方法.它以一个初始点作为根节点,通过随机采样增加叶子节点的方式,生成一个随机扩展树,当随机树中的叶子节点包含了目标点或进入了目标区域,便可以在随机树中找到一条由从初始 ...