Python更多控制流工具(一)

4.1. if Statements

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

if语句可能是最常见的控制流语句了,例如:

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

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.

可以有0个或多个elif部分,else部分也是可选的。关键字elif是 else if的简称,它能很有效的避免过多的缩排。if...elif...elif 可以使其他语言的switch...case语句。(Python没有switch语句)。

4.2. for Statements

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

在Python中,for语句和你使用的C或Pascal语言有点不同,在Pascal语言中,for语句总是以某个数的等差数列迭代,在C语言中,用户可以定义循环条件和步差。在Python中,for语句是依次遍历序列的每一个元素。例如:

>>> # Measure some strings:
... words = [‘cat‘, ‘window‘, ‘defenestrate‘]
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

如果你想在迭代的同时修改序列(例如复制某个元素),建议你先复制序列。因为迭代一个序列并不会隐式的复制序列。下面的切片操作非常方便用来复制序列:

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
[‘defenestrate‘, ‘cat‘, ‘window‘, ‘defenestrate‘]

4.3. The range() Function

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

如果你需要变量一个数字序列,那么内置的函数rang()排的上用场。它会产生一个数列。

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):

range()函数也是遵守前闭后开原则;range(10)产生10个值(0到9),可以指定数值序列起始值,或指定不同的步差(步差可以是负数)

range(5, 10)
   5 through 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

To iterate over the indices of a sequence, you can combine range() and len() as follows:

可以按索引序列来迭代,你可以结合range()和len()函数:

>>> a = [‘Mary‘, ‘had‘, ‘a‘, ‘little‘, ‘lamb‘]
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.

更多情况下,使用enumerate()函数会更方便一些,见Looping Techniques

A strange thing happens if you just print a range:

如果你用print()函数直接打印rang()函数,会看到一个奇怪的现象:

>>> print(range(10))
range(0, 10)

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

我们可能觉得rang()应该是返回一个类似于列表的对象,但其实不是的。当你迭代它的时候,它返回的是所期望序列的连续的元素,但它不是一个列表,这是为了节约空间。

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:

我们称这样的对象叫做:可迭代的iterable,我们其实已经看到 for语句也是一个iterator。函数list()也是;它以迭代对象作为参数返回一个列表:

>>> list(range(5))
[0, 1, 2, 3, 4]

Later we will see more functions that return iterables and take iterables as argument.

下面,我们会看到更多函数返回 一个迭代对象或将迭代对象作为参数。

4.4. break and continue Statements, and else Clauses on Loops

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

和C语言程序一样,break语句用来跳出最近的for或while循环。

循环语句可以有一个else子句;当循环跳出循环条件之后就执行else语句。但是如果是通过break跳出循环的,则不执行else语句。看下面的例子,搜寻质数:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, ‘equals‘, x, ‘*‘, n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, ‘is a prime number‘)
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)

(是的,这是正确的代码,仔细看,else子句是属于里面的for循环的,而不是属于if语句)

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.

else子句另一个应用最普遍的地方是和try语句一起使用:当没有异常发生的时候,则会使用到try语句的else子句。更多try语句和异常,请查阅异常处理。

4.5. pass Statements

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

pass语句作用:不做任何事情。它通常在当某个语句需要包含一条语句,但又不需要做任何事情的时候使用。例如:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

This is commonly used for creating minimal classes:

最常见的使用是创建最简单的类:

>>> class MyEmptyClass:
...     pass
...

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:

另一个使用pass的地方是:当你写新代码时,给函数或条件体作为一个占位符,这样允许你保持该函数可运行或更抽象。pass语句直接被忽略:

>>> def initlog(*args):
...     pass   # Remember to implement this!
...
时间: 2024-10-11 18:11:49

Python更多控制流工具(一)的相关文章

Python更多控制流工具(二)

4.6. Defining Functions We can create a function that writes the Fibonacci series to an arbitrary boundary: 我们创建一个斐波那契数列的函数: >>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n."""

[转载]Python 包管理工具解惑

原文链接:http://zengrong.net/post/2169.htm Python 包管理工具解惑 python packaging 一.困惑 作为一个 Python 初学者,我在包管理上感到相当疑惑(嗯,是困惑).主要表现在下面几个方面: 这几个包管理工具有什么不同? distutils setuptools distribute disutils2 distlib pip 什么时候该用pip,什么时候该用 setup.py ,它们有关系么? easy_install.ez_setup

Python静态检查工具

Python是一门动态语言.在给python传参数的时候并没 有严格的类型限制.写python程序的时候,发现错误经常只能在执行的时候发现.有一些 错误由于隐藏的比较深,只有特定逻辑才会触发,往往导致需要花很多时间才能将语法错误慢慢排查出来.其实有一些错误是很明显的,假如能在写程序的时候发现这些错误,就能提高工作效率. 注:习惯了C/C++等编译语言,使用像Python这种动态语言,总有点不放心,特别是搭建比较大的系统的时候.Python静态语法检查工具就出现了. Pyflakes(错误检查利器

Python渗透测试工具合集

Python渗透测试工具合集 如果你热爱漏洞研究.逆向工程或者渗透测试,我强烈推荐你使用 Python 作为编程语言.它包含大量实用的库和工具, 本文会列举其中部分精华. 网络 Scapy, Scapy3k: 发送,嗅探,分析和伪造网络数据包.可用作交互式包处理程序或单独作为一个库. pypcap, Pcapy, pylibpcap: 几个不同 libpcap 捆绑的python库 libdnet: 低级网络路由,包括端口查看和以太网帧的转发 dpkt: 快速,轻量数据包创建和分析,面向基本的

Python 包管理工具解惑

Python 包管理工具解惑 本文链接:http://zengrong.net/post/2169.htm python packaging 一.困惑 作为一个 Python 初学者,我在包管理上感到相当疑惑(嗯,是困惑).主要表现在下面几个方面: 这几个包管理工具有什么不同? distutils setuptools distribute disutils2 distlib pip 什么时候该用pip,什么时候该用 setup.py ,它们有关系么? easy_install.ez_setup

python环境和工具

1.版本问题 python2.X和python3.X是不兼容,所以选择如果选择了2.X版本,那么为了避免兼容性的问题,在以后使用其他python库或者工具时,也需要选择相对应的版本. 下载地址:https://www.python.org/ 2.开发工具IDLE IDLE是python自身附带使用tkinter创建的图形化的交互式环境. 3.用tkinter编写GUI tkinter是python自带的用于GUI编程的库,是对图形库TK的封装,跨平台. 4.数值计算库NumPy和SciPy Nu

Python包管理工具小结

此文已由作者张耕源授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 作为一名接触Python有一段时间的初学者,越来越体会到Python的方便之处,它使人能更 多的关注业务本身的逻辑,而不用太纠结语言层面的技巧与细节.然而,随着服务的规模 变得越来越大,如何方便快速地制作与发布一个Python软件包则越来越成为一个让人头疼 地问题,特别是像Openstack这种相对复杂.各种依赖也很多的Python项目,到目前也没有 发现特别完美的解决方案.这里将尝试对Python的包管

python代码检查工具pylint 让你的python更规范

1.pylint是什么? Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8,具体信息,请参阅参考资料)和有潜在问题的代码.目前 Pylint 的最新版本是 pylint-0.18.1. Pylint 是一个 Python 工具,除了平常代码分析工具的作用之外,它提供了更多的功能:如检查一行代码的长度,变量名是否符合命名标准,一个声明过的接口是否被真正实现等等. Pylint 的一个很大的好

windows安装python包管理工具pip

windows安装python包管理工具pip     pip 是一个Python包管理工具,主要是用于安装 PyPI 上的软件包,可以替代 easy_install 工具. 一.前期准备 首先确认windows机器上面是否已经安装好了python.在cmd中输入python --version和python看看是否有反应 如上面所示,表示已经在windows平台上面搭建好了python环境. 二.下载安装 1.到官网去https://pypi.python.org/pypi/pip#downl