4 Apr 2009

Python学习笔记 - 5:程序流程控制(循环和条件语句)

本文主要有:程序流程控制(循环和条件语句)

This article is mainly about programme flow control

Python中的程序逻辑控制与其他语言无二,主要是循环和条件.
(注意Python中并无switch语句,需要使用if...else...)

As same as the other popular programming languages, Python uses
Loop and Conditional statements for programme control.
(Note: There's no switch statement in python, you have to use
if...else... instead.)



记住: 对所有循环,如果需要用到range(),请永远用xrange()来代替,以便得到较高的效率.xrange()并不会立即返回一个列表对象,只有在需要的时候才会计算列表中的某个值.

Note: for all loops, NEVER use range(), but xrange() instead. xrange() has much better performance than range(), due to it does not return a list object immediately, the values would not be computed until they have to be.

循环结构:
2种循环分别是For循环和While循环.
格式如下:

Loop:
There are two types of loops: For loop and While loop.
Both of them can be used as Non-nested and Nested.

1. 非嵌套格式

1. Non-nested structure

for condition:
do something
...

while condition:
do something
...


2. 嵌套格式

2. Nested structure

for condition1:
do something1
...
for condition2:
do something2
...
for condition3:
do something3
...
...
...

while condition1:
do something1
...
while condition2:
do something2
...
while condition3:
do something3
...
...
...


下面是个例子:

An example:

>>> a = range(4)
>>> for i in a:
print 'i= %d.' % i

i= 0.
i= 1.
i= 2.
i= 3.
>>> i
3
>>> i=0
>>> while i in a:
print 'i=%d.' % i
i+=1

i=0.
i=1.
i=2.
i=3.
>>> j = 1000000
>>> j = 10000
>>> i = 1
>>> while i in xrange(j):
print 'i=%d.' % i
i+=1

i=1.
i=2.
i=3.
i=4.
i=5.
...
i=9999.


如果你想在循环过程中加以控制,需要使用break与continue.
break: 跳出循环/如果是嵌套循环,只能跳出break所在层
continue: 结束本次循环,继续执行下一次循环

You have to use break and continue to control the programme within loops.
break: break the loop/ONLY break the current layer loop if using in nested loops
continue: skip the current loop, go on to execute the next one

条件结构: if...else...,结构如下:

Conditional statement, if...else..., the structure is:

if condition:
do something1
else:
do something2


为了方便:

for short:

if condition: do something1
else: do something2


测试如下:

An example:

>>> a = [0,1,2,3]
>>> if i in a:
print 'i is in a.'
else:
print 'i is not in a.'

i is not in a.

No comments :

Post a Comment