条件语句
if expression:
statements
elif expression:
statements
elif expression:
statements
...
else:
statements
示例:
#coding:utf8
# 输入一个整数与20进行比较
number = raw_input('please enter an Integer:')
if number > 20:
print "The number you enter is more than 20!"
elif number < 20:
print "The number you enter is less than 20!"
else:
print "The number you enter is equal to 20!"
如果不需要判断if条件外的其它情形,条件语句中的else从句和elif从句可以省略. pass语句用于不需要做任何事的特殊情形:
if expression:
pass
else:
statements
上面这段代码也等价于:
if !expression:
statements
循环语句
Python的循环语句有for循环和while循环.
for循环
for i in s:
statements
for语句反复迭代一个序列中的元素,直到迭代完序列中最后一个元素。
示例1:
#coding:utf8
import os
# 列出当前目录下所有文件和文件夹名称
strDir = "D:\\out"
for fileName in os.listdir(strDir):
print fileName
以上示例执行结果(其中project是文件夹名,其它是文件名):
hello.py
hellobat.bat
out.zip
project
如果序列中的每个元素都是元素个数统一的元组,你可以以下面这样的形式应用for语句。(s必须为一个元组的序列,每个序列有三个元素,每次循环中,元组的三个元素的值分别赋值给x,y,z)
示例2:
#coding:utf8
import os
# 列出某个目录其子目录下所有文件的路径
targetDir = "D:\\out"
for root,dirs,files in os.walk(targetDir):
for file in files:
fileDir = root + os.sep + file
print fileDir
以上示例执行结果:
D:\out\hello.py
D:\out\hellobat.bat
D:\out\out.zip
D:\out\project\hello.py
while循环
while expression:
statements
while语句执行循环块中的语言,直到表达式为假。
示例:
count = 0
while (count < 8):
print 'The count is:', count
count = count + 1
以上示例的执行结果:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
break 和continue语句
Python 还支持在while和for循环语句中使用break和continue语句来跳出循环。
- break跳出整个循环。即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。如果使用嵌套循环,则终止循环语句,停止执行最深层的循环,并开始执行下一行代码。
- continue 语句跳出本次循环,即跳过当前循环的剩余语句,然后继续进行下一轮循环。
示例1:
#coding:utf8
# 列出列表中第一个包含字符’B’的字符串
strList = ["Apple","Butter","Banana","Blackberry"]
for strName in strList:
if "B" in strName:
print strName
break
以上示例执行结果:
Butter
示例2:
#coding:utf8
# 列出列表中长度为6的字符串,忽略长度不等于6的字符串
strList = ["Apple","Butter","Banana","Blackberry"]
for strName in strList:
if len(strName) <> 6:
continue
print "The string length of '" + strName + "' is 6."
以上示例执行结果:
The string length of 'Butter' is 6.
The string length of 'Banana' is 6.
else语句
循环中的else语句只在循环正常完成后运行(for或while循环),或者在循环条件不成立时立即运行(仅while循环),或者迭代序列为空时立即执行(仅for循环)。如果循环使用break语句退出的话,else语句将被忽略。
示例(while循环):
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
以上示例执行结果:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
示例(for循环):
strList = ["veb","lest","text"]
for x in strList:
if x == 'Foo':
break
else:
print "Foo is not in the list!"
以上示例执行结果:
Foo is not in the list!
注意:Python 没有goto语句和case语句.