if语句
一、if语句的格式
语句块必须有相同的缩进。
语句块必须比if,elif,else多一层缩进
# 如果条件成立则执行语句块1,# 否则 如果条件2成立则执行语句块2# 其他情况执行语句块3# elis和else部分是可选的if 条件1: 语句块1elif 条件2: 语句块2else: 语句块3
二、实例
i = 10if i == 3: print ' i 是3.' print "我也是在if之后执行的。"elif i < 3: print 'i < 3'else: print '其他情况。'print '打印结束。'
三、注意事项
1. python中没有switch语句, switch可以使用if...elif...else实现2. if, elif, else之后必须要有冒号(:), 之后的代码需要增加一层缩进
while循环
只要在一个条件为真的情况下,while语句允许你重复执行一块语句。while语句是所谓 循环 语句的一个例子。while语句有一个可选的else从句。
使用while语句
例6.2 使用while语句
代码如下
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
(源文件:code/while.py)
输出
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done
for语句
for..in是另外一个循环语句,它在一序列的对象上 递归 即逐一使用队列中的每个项目。我们会在后面的章节中更加详细地学习序列。
使用for语句
例6.3 使用for语句
代码如下
#!/usr/bin/python
# Filename: for.py
for i in range(1, 5):
print i
else:
print 'The for loop is over'
输出
$ python for.py
1
2
3
4
The for loop is over
break和continue语句
break语句是用来 终止 循环语句的,即哪怕循环条件没有称为False或序列还没有被完全递归,也停止执行循环语句。
一个重要的注释是,如果你从for或while循环中 终止 ,任何对应的循环else块将不执行。
使用break语句
例6.4 使用break语句
代码如下
#!/usr/bin/python
# Filename: break.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后 继续 进行下一轮循环。
使用continue语句
例6.5 使用continue语句
代码如下
#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'
# Do other kinds of processing here...
(源文件:code/continue.py)
输出
$ python continue.py
Enter something : a
Enter something : 12
Enter something : abc
Input is of sufficient length
Enter something : quit