因此,流程控制其实就是通过if之类的关键字,来对某些条件进行判断,并根据判断的结果做出不同的行为,从而让程序具备了基本的 应变能力 ,当你的程序对所有可能的情况都写了相应的代码的时候,那么你的程序就会变得少BUG,以及更加智能化,当然运行起来也会相对变慢,因为它要对所有情况都进行判断,每次判断都会产生一定的开销。

    页面导航: 英文教程的下载地址:

    本篇文章是根据英文教程《Python Tutorial》来写的学习笔记。该英文教程的下载地址如下:

    百度盘地址:http://pan.baidu.com/s/1c0eXSQG

    DropBox地址:点此进入DropBox链接

    Google Drive:点此进入Google Drive链接

    这是学习笔记,不是翻译,因此,有些内容,作者会略过。以下记录主要是根据英文教程的第六章来写的。(文章中的部分链接,可能需要通过代理访问!)

概述:

    其实在之前的章节中,已经多次提到过流程控制结构,例如,下面的例子:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 3
>>> b = 1
>>> if a > b:
...  print 'a > b'
... 
a > b
>>> quit()
[email protected]:~$ 


    上面代码中,先将变量a设置为3,变量b设置为1,通过if关键字来判断a的值是否大于b,如果a大于b,则执行if下面的print语句,从而打印出'a > b'的字符串信息,如果a小于或等于b,则不会去执行if后面的print语句。

    因此,流程控制其实就是通过if之类的关键字,来对某些条件进行判断,并根据判断的结果做出不同的行为,从而让程序具备了基本的"应变能力",当你的程序对所有可能的情况都写了相应的代码的时候,那么你的程序就会变得少BUG,以及更加智能化,当然运行起来也会相对变慢,因为它要对所有情况都进行判断,每次判断都会产生一定的开销。

    下面我们就来看下if语句的具体语法。(下面内容中提到的"对象"的概念,在上一篇文章的比较运算符部分已经介绍过了,这里就不多说了)

if语句:

    最基本的if语法,如下所示:

if expression:
    statement(s)


    if后面的expression可以是任意类型的表达式,可以是3 * 1这类的计算表达式,也可以是3 > 1这类的比较表达式,只要表达式返回一个具有特定值的对象,供if作判断即可。当表达式返回的对象是True、非零的数字、非空的字符串、或者非空的集合(如列表等)时,那么就会执行statement(s)部分的代码块。如下所示:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if True: 
...  print True
... 
True
>>> if 3 > 1:
...  print 3 > 1
... 
True
>>> if 123:
...  print '123'
... 
123
>>> if 'hello world':
...  print 'hello'
... 
hello
>>> if [1, 2, 3] :
...  print '[1, 2, 3]'
... 
[1, 2, 3]
>>> quit()
[email protected]:~$ 


    当表达式返回的对象是False、零、空字符串、空集合、或者None时,则statement(s)部分的代码块就不会执行。如下所示:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if False:
...  print False
... 
>>> if 3 < 1:
...  print False
... 
>>> if 0:
...  print '0'
... 
>>> if '':
...  print 'null string'
... 
>>> if []:
...  print 'null list'
... 
>>> if None:
...  print 'None'
... 
>>> type(None)
<type 'NoneType'>
>>> quit()
[email protected]:~$ 


    可以看到,上面输出中,if后面的代码块都没被执行,这和预期的是一致的,另外,None是Python中NoneType类型的对象,它与True,False一样只是一个对象,if之类的关键字可以根据这些对象作出不同的判断,以执行不同的代码。

    从上面的例子中,可以看到,if与用于判断的表达式之间需要有空格分开,这是因为,如果if和表达式连在一起的话,就容易产生语法错误,如下所示:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if3 > 1:
  File "<stdin>", line 1
    if3 > 1:
           ^
SyntaxError: invalid syntax
>>> quit()
[email protected]:~$ 


    可以看到,if与3 > 1的表达式连在一起就产生了语法错误,因为,if3变为了一个普通的标识符,而不再是if关键字了。如果不想在if与表达式之间使用空格的话,表达式与if关键字之间需要有括号、引号之类的分隔符,也就是让if不会受到表达式中的字符的干扰而变为另一个标识符即可,如下所示:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if[1,2,3]:
...  print '[1,2,3]'
...      
[1,2,3]
>>> if(3 > 1):
...  print '3 > 1'
... 
3 > 1
>>> if'hello':
...  print 'hello'
... 
hello
>>> quit()
[email protected]:~$


    还有一点需要注意的是,if语句的最后需要以冒号结束,如果没有冒号也会产生语法错误(因为冒号容易被忽视,因此,这种错误经常会发生):

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if(3 > 1)
  File "<stdin>", line 1
    if(3 > 1)
            ^
SyntaxError: invalid syntax
>>> quit()
[email protected]:~$ 


    上面在if语句的最后缺少了冒号,就抛出了语法错误。

if...else语句:

    如果我们想让if在表达式返回True时,执行一个代码块,而表达式返回False时,执行另一个代码块的话,就需要用到if...else语句了,例如,下面的例子:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if True:
...  print True
... else:
...  print False
... 
True
>>> if False:
...  print True
... else:
...  print False
... 
False
>>> quit()
[email protected]:~$ 


    上面输出显示,当if接收到True对象时,就会执行if下面的代码块。当if接收到False对象时,则会转去执行else下面的代码块。

    同样的,当if后面的表达式返回的对象是非零的数字、非空的字符串、或非空的集合时,都可以当作是True。当表达式返回的对象是零、空字符串、空集合、或None时,都可以当作是False。

    else与if一样,必须以冒号结束。此外,在之前的例子中,if...else下面的代码块部分都只演示了一条语句,其实代码块可以由多条语句组成:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if 3 > 1:
...  print '3 > 1 is '
...  print True
... else:
...  print '3 > 1 is '
...  print False
... 
3 > 1 is 
True
>>> quit()
[email protected]:~$ 


    只要确保,同一个代码块里的多条语句具有相同的缩进即可。

if...elif...else语句:

    当我们想对多个表达式进行判断,并针对这些表达式返回的结果,执行不同的代码块时,就可以使用if...elif...else语句,例如,下面的例子:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 60 
>>> if a >= 90:
...  print 'you are great, your score is '   
...  print a
... elif a >= 80:
...  print 'you are good, your score is '
...  print a
... elif a >= 70:
...  print 'you are normal, your score is '
...  print a
... elif a >= 60:
...  print 'pass, your score is '
...  print a
... else:
...  print 'sorry, not pass, your score is '
...  print a
... 
pass, your score is 
60
>>> quit()
[email protected]:~$ 


    在上面的交互式输入界面中,先将变量a的值设为了60,然后先通过if a >= 90来判断a是否大于或等于90,如果是则打印出'you are great...'的信息,如果a小于90,则由elif a >= 80来判断a是否大于或等于80,如果符合条件,就打印出'you are good...'的信息,如果a小于80,则再进入下一个elif,由elif a >= 70来判断其是否大于或等于70,以此类推,当之前的if和elif都判断为False时,最后才会执行else后面的代码块。

    由于a为60,因此,就会在第三个elif语句上判断通过,从而打印出'pass, your score is...'的信息。

    因此,if...elif...else语句的作用就是,依次对 if 和 elif 的条件表达式进行判断,当某个表达式判断通过时,就执行其后的代码块,当所有的表达式都判断不通过时,才执行else后面的代码块。

    另外,if...elif...else语句中的elif和else都是可选的,当没有elif时,它就变为之前提到的if...else结构了。当既没有elif,又没有else时,它就变为之前提到的单一的if语句了。当没有else时,它就会变为if...elif语句:

[email protected]:~$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 60
>>> if a >= 90:
...  print 'you are great, your score is '
...  print a
... elif a >= 80:
...  print 'you are good, your score is '
...  print a
... elif a >= 70:
...  print 'you are normal, your score is '
...  print a
... 
>>> quit()
[email protected]:~$ 


    当没有else关键字时,如果if与elif对应的表达式都判断失败时,程序就会跳过这段if...elif结构,而去执行其后的代码(如果其后还有可供执行的代码的话),因此,上面例子在执行时,就不会打印出任何信息,因为变量a的值不符合if...elif里的任何一个表达式,也就跳过了所有的print语句。

    需要注意的是:else部分必须放在if...elif...else结构的最后,且该结构中最多只能有一个else。此外,elif部分也必须以冒号结束,且elif必须位于if之后。

    Python并不提供单独的switch...case结构,要实现该功能,只能通过if...elif...else结构来模拟。例如,在C语言中,我们可以使用如下所示的代码:

int val = 200;
switch(val)
{
case 100:
  printf("the val is 100 \n");
  break;
case 200:
  printf("the val is 200 \n");
  break;
case 300:
  printf("the val is 300 \n");
  break;
case 400:
  printf("the val is 400 \n");
  break;
default:
  printf("invalid val \n");
  break;
}


    要在Python中实现上述C代码的功能的话,只有通过if...elif...else的结构来实现,如下所示:

val = 200
if val == 100:
 print 'the val is 100'
elif val == 200:
 print 'the val is 200'
elif val == 300:
 print 'the val is 300'
elif val == 400:
 print 'the val is 400'
else:
 print 'invalid val'


    在某些简单的代码中,也可以用dict词典来实现switch...case结构,如下所示:

[email protected]:~/Pytest/ch6$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> val = 'b'
>>> {'a' : 1,
...  'b' : 2,
...  'c' : 3,
...  'd' : 4
... }[val]
2
>>> quit()
[email protected]:~/Pytest/ch6$ 


    不过,在词典中无法直接使用print之类的语句,在 http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python 链接中,有更多的使用词典及其他方式来实现switch...case结构的例子。

嵌套if语句:

    和其他语言一样,python的if语句是可以嵌套使用的,其嵌套语法类似如下所示:

if expression1:
	statement(s)
	if expression2:
		statement(s)
	elif expression3:
		statement(s)
	else:
		statement(s)
elif expression4:
	statement(s)
else:
	statement(s)


    上面在if代码块里又嵌套了一层if...elif...else结构,这样,当expression1表达式判断通过后,还可以继续对expression2及expression3表达式进行判断,从而可以对多个表达式进行综合判断,这样就使得程序的流程控制变得更加灵活。

    当然也可以在elif或者else结构中嵌套if...elif...else结构,还可以进行更多层次的嵌套,类似如下语法:

if expression1:
	statement(s)
	if expression2:
		if expression3:
			statement(s)
		elif expression4:
			statement(s)
		else:
			statement(s)
		statement(s)
	elif expression5:
		statement(s)
	else:
		statement(s)
elif expression6:
	statement(s)
	if expression7:
		statement(s)
	elif expression8:
		statement(s)
	else:
		statement(s)
else:
	statement(s)


    只要注意,在嵌套时,同一代码块里的各语句,必须具有相同的缩进即可。

    下面是一个完整的嵌套if语句的例子:

var = 100
if var > 90:
	print "Expression value is great than 90"
	if var == 95:
		print "Which is 95"
	elif var == 96:
		print "Which is 96"
	elif var == 100:
		print "Which is 100"
elif var > 60:
	print "Expression value is great than 60 and less than or equal 90"
else:
	print "invalid value"

print "Good bye!"


    我们将上述代码保存到test.py文件中,运行结果如下:

[email protected]:~/Pytest/ch6$ python test.py
Expression value is great than 90
Which is 100
Good bye!
[email protected]:~/Pytest/ch6$ 


单行if结构:

    如果if代码块中只包含单条语句时,可以将该语句和if结构写在一行中:

[email protected]:~/Pytest/ch6$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if(3 > 1): print (3 > 1)    
... 
True
>>> quit()
[email protected]:~/Pytest/ch6$ 


    上面if后面的代码块里只有一个print语句,那么我们可以将其和if结构写在一行,当然,其实多条语句也可以写在一行,只不过,各语句之间要通过分号来隔开:

[email protected]:~/Pytest/ch6$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if(3 > 1): print (3 > 1); print 'hello'; print 'world!'
... 
True
hello
world!
>>> quit()
[email protected]:~/Pytest/ch6$ 


    上面的写法同样适用于elif结构:

[email protected]:~/Pytest/ch6$ python
Python 2.7.8 (default, Dec 10 2014, 22:05:07) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if(3<1): print (3<1)  
... elif(3>1): print (3>1); print 'welcome to python'
... 
True
welcome to python
>>> quit()
[email protected]:~/Pytest/ch6$ 


    以上就是流程控制相关的内容。

    OK,休息,休息一下 o(∩_∩)o~~

    良好的健康状况和高度的身体训练,是有效的脑力劳动的重要条件。
----(前苏联)杰普莉茨卡娅
 
上下篇

下一篇: Python循环语句

上一篇: Python基本的操作运算符

相关文章

Python中的异常

Python三角函数

Python基本的I/O操作 (四)

Python字符串相关的函数

Python元组类型及相关函数

Python基本的I/O操作 (二)