您的位置:首页 > 编程语言 > Python开发

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语法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: