设为首页 收藏本站
查看: 976|回复: 0

[经验分享] Python更多控制流工具(一)

[复制链接]

尚未签到

发表于 2015-12-1 09:10:14 | 显示全部楼层 |阅读模式
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)
...
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!
...

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145695-1-1.html 上篇帖子: python mongodb压力测试脚本 下篇帖子: Python模块学习之bs4
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表