7.1 Python条件语句
• Python编程if 语句用于控制程序的执行,基本形式为:
if 判断条件:
-- 执行语句……
else:
-- 执行语句……
7.2 Python条件表达式
if-else
pass 语句 – 不做任何事时使用
if 语句的判断条件可以用>(大于)、=(大于等于)、<=(小于等于)来表示其关系。
当判断条件为多个值时,可以使用以下形式:
if 判断条件1:
-- 执行语句1……
elif 判断条件2:
-- 执行语句2……
elif 判断条件3:
-- 执行语句3……
else:
-- 执行语句4……
elif语句
逻辑表示式:and, or, not
7.3 Python循环语句
• Python提供了for循环和while循环,在Python中没有do..while循环。
7.3.1 Python循环控制语句
• 循环控制语句可以更改语句执行的顺序。Python支持以下循环控制语句。
7.3.2 Python While循环语句
• Python编程中while语句用于循环执行程序。
• 执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零或非空(null)值均为true。
• 当判断条件false时,循环结束。
7.4 循环(loops)
• while语法
7.4.1 Python While循环语句
7.4.2 无限循环
• 如果条件判断语句永远为true,循环将会无限的执行下去
7.4.3 循环使用else语句
• 在Python中while … else在循环条件为false时执行else语句块。
7.4.4 循环简单语句组
• 类似if语句的语法,如果while循环体中只有一条语句,可以将该语句与
while写在同一行中。无限循环可以使用CTRL+C中断循环。
7.4.5 Python for 循环语句
• Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
• for语法 (迭代访问列表元素)
7.4.6 循环使用else语句
• 在Python中for … else表示for中的语句和普通的没有区别,else中的语句会在循环正常执行完(即for不是通过break跳出而中断的)的情况下执行,while …else也是一样。
7.4.7 Python循环嵌套
• Python语言允许在一个循环体里面嵌入另一个循环。
• 可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,也可以在for循环中嵌入while循环。
7.4.8 Python break语句
7.4.9 Python continue语句
7.4.10 Python pass语句
• Python pass是空语句,是为了保持程序结构的完整性。
7.5 import与from...import
• 在Python用import或者from...import来导入相应的模块。
• 将整个模块(somemodule)导入,格式为:import somemodule
• 从某个模块中导入某个函数,格式为:
from somemodule import somefunction
• 从某个模块中导入多个函数,格式为:
from somemodule import firstfunc, secondfunc, thirdfunc
• 将某个模块中的全部函数导入,格式为:
from somemodule import *
7.6 实验
7.6.1控制结构
In:
if a > b:
print("ok")
else:
pass
In:
if a > b:
print("ok")
elif a < b:
pass
elif a == b:
pass
else:
pass
7.6.2 循环结构
while
In:
a = 10
while a > 0:
print("当前值:{}".format(a))
a -= 1
out:
当前值:10
当前值:9
当前值:8
当前值:7
当前值:6
当前值:5
当前值:4
当前值:3
当前值:2
当前值:1
In:
import time
In:
#无限循环
while True:
if a == 10:
print("check")
else:
print("Not check")
time.sleep(1)
out:
Not check
Not check
Not check
Not check
Not check
Not check
Not check
Not check
Not check
Not check
Not check
Not check
Not check
out:
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
in
5 else:
6 print("Not check")
----> 7 time.sleep(1)
out:
KeyboardInterrupt:
In:
a = 10
while a > 0:
print("当前值:{}".format(a))
a -= 1
else:
print("a小于等于0")
out:
当前值:10
当前值:9
当前值:8
当前值:7
当前值:6
当前值:5
当前值:4
当前值:3
当前值:2
当前值:1
a小于等于0
In:
#break
a = 10
while a > 0:
print("当前值:{}".format(a))
a -= 1
if a == 5:
break
out:
当前值:10
当前值:9
当前值:8
当前值:7
当前值:6
In:
a = 10
while a > 0:
a -= 1
if a % 2 == 0:
continue
print("当前值:{}".format(a))
out:
当前值:9
当前值:7
当前值:5
当前值:3
当前值:1
7.6.3 For
In:
for ch in "dylan":
print(ch)
out:
d
y
l
a
n
In:
for i in range(1,10,2):
print(i)
out:
1
3
5
7
9
In:
for i in range(1,10):
print("I:{}".format(i))
for j in range(0,i):
print(i,j)
if j % 2 == 0:
break #跳出小循环
print("checking")
else:
print("ending")
out:
I:1
1 0
I:2
2 0
I:3
3 0
I:4
4 0
I:5
5 0
I:6
6 0
I:7
7 0
I:8
8 0
I:9
9 0
ending
In:
for ch in "dylan":
pass #什么也没干
print(ch)
out:
d
y
l
a
n