04 python基础 流程控制
2018-02-23 15:36
471 查看
import os # 1 print('<[1]> time module start') # 2 class ClassOne(): print('<[2]> ClassOne body') # 3 def __init__(self): # 10 print('<[3]> ClassOne.__init__') def __del__(self): print('<[4]> ClassOne.__del__') # 101 def method_x(self): # 12 print('<[5]> ClassOne.method_x') class ClassTwo(object): print('<[6]> ClassTwo body') # 4 class ClassThree(): print('<[7]> ClassThree body') # 5 def method_y(self): # 16 print('<[8]> ClassThree.method_y') class ClassFour(ClassThree): print('<[9]> ClassFour body') # 6 def func(): print("<func> function func") if __name__ == '__main__': # 7 print('<[11]> ClassOne tests', 30 * '.') # 8 one = ClassOne() # 9 one.method_x() # 11 print('<[12]> ClassThree tests', 30 * '.') # 13 three = ClassThree() # 14 three.method_y() # 15 print('<[13]> ClassFour tests', 30 * '.') # 17 four = ClassFour() four.method_y() print('<[14]> evaltime module end') # 100
在Python中没有switch – case语句。
1.if
if语句的一般形式如下所示:
if 表达式1: 语句 if 表达式2: 语句 elif 表达式3: 语句 else 语句 elif 表达式4: 语句 else: 语句
2.while
没有其它语言的do…while语句
n = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter counter += 1 print("1 到 %d 之和为: %d" % (n,sum))
while的else从句:
while循环还可以增加一个else从句。当while循环正常执行完毕,会执行else语句。但如果是被break等机制强制提前终止的循环,不会执行else语句。注意else与while平级的缩进方式!
number = 10 i = 0 # i = 11 while i < number: print(i) i += 1 else: print("执行完毕!")
下面是被打断的while循环,else不会执行:
number = 10 i = 0 while i < number: print(i) i += 1 if i == 7: break else: print("执行完毕!")
for循环:
一般用法:
sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x print(sum)
for循环的else 子句:
与while一样,for循环也可以有else子句。同样是正常结束循环时,else子句执行。被中途break时,则不执行。
循环的嵌套
if判断可以嵌套,while和for当然也可以嵌套。但是建议大家不要嵌套3层以上,那样的效率会很低。下面是一个嵌套for循环结合else子句的例子:
# 这是一个判断质数的程序 for n in range(2, 100): for x in range(2, n): if n % x == 0: print(n, '等于', x, '*', n//x) break else: # 循环中没有找到元素 print(n, ' 是质数')
break语句
continue语句
Python没有goto语法
相关文章推荐
- Python基础—04-流程控制
- 黑马程序员——零基础学习iOS开发——04 c语言:基本运算、流程控制、函数
- Python基础05 流程控制
- Day1 - Python基础1 介绍、基本语法、流程控制
- 浅析Python基础-流程控制
- Python--基础学习--流程控制
- Day1 Python基础学习——概述、基本数据类型、流程控制
- Python基础6- 流程控制之if条件语句
- python_基础总结1 python由来 字符编码 注释 pyc文件 python变量 导入模块 获取用户输入 流程控制if while
- Python基础1 基本语法、流程控制
- Python基础7- 流程控制之循环
- Python基础概念_4_控制流程
- Python基础--流程控制
- Unit04: JavaScript 概述 、 JavaScript 基础语法 、 流程控制
- 第二章(1.4)Python基础知识(流程控制)
- Python基础--流程控制
- python基础-变量、数据类型、input、格式化、运算符、流程控制
- python知识点(2)——python基础 流程控制
- python基础之流程控制、数字和字符串处理
- PHP基础----04流程控制