您的位置:首页 >> 编程开发 >> C/C++ >> 正文
C/C++ RSS
 

Python Tutorial(2)

http://www.rdxx.com 05年09月13日 23:28 Blog.ChinaUnix.net 我要投稿

关键词: Tutorial , Python
从第四章开始

4. 深入流程控制 More Control Flow Tools

Besides the while statement just introduced, Python knowsthe usual control flow statements known from other languages, withsome twists.

除了前面介绍的 while 语句,Python 还从别的语言中借鉴了一些流程控制功能,并有所改变。


4.1 if 语句 if Statements

Perhaps the most well-known statement type is theif statement. For example:

也许最有名的是 if 语句。例如:

>>> x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...

There can be zero or more elif parts, and theelse part is optional. The keyword `elif' isshort for `else if', and is useful to avoid excessive indentation. Anif ... elif ... elif ... sequenceis a substitute for the switch orcase statements found in other languages.

可能会有零到多个 elif 部分,else 是可选的。关键字“elif” 是“ else if ”的缩写,这个可以有效避免过深的缩进。if ... elif ... elif ... 序列用于替代其它语言中的 switch 或 case 语句。


4.2 for 语句 for Statements

The for statement in Python differs a bit fromwhat you may be used to in C or Pascal. Rather than alwaysiterating over an arithmetic progression of numbers (like in Pascal),or giving the user the ability to define both the iteration step andhalting condition (as C), Python'sfor statement iterates over the items of anysequence (a list or a string), in the order that they appear inthe sequence. For example (no pun intended):

Python 中的 for 语句和 C 或 Pascal 中的略有不同。通常的循环可能会依据一个等差数值步进过程(如Pascal)或由用户来定义迭代步骤和中止条件(如 C ),Python 的 for 语句依据任意序列(链表或字符串)中的子项,按它们在序列中的顺序来进行迭代。例如(没有暗指):

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12

It is not safe to modify the sequence being iterated over in the loop(this can only happen for mutable sequence types, such as lists). Ifyou need to modify the list you are iterating over (for example, toduplicate selected items) you must iterate over a copy. The slicenotation makes this particularly convenient:

在迭代过程中修改迭代序列不安全(只有在使用链表这样的可变序列时才会有这样的情况)。如果你想要修改你迭代的序列(例如,复制选择项),你可以迭代它的复本。通常使用切片标识就可以很方便的做到这一点:

>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']


4.3 range() 函数 The range() Function

If you do need to iterate over a sequence of numbers, the built-infunction range() comes in handy. It generates listscontaining arithmetic progressions:

如果你需要一个数值序列,内置函数range()可能会很有用,它生成一个等差级数链表。

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The given end point is never part of the generated list;

上一页 下一页


 
 
标签: Tutorial , Python 打印本文
 
 
  相关资讯
RSS
 
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站