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

[经验分享] Python Tutorial 学习(四)--More Control Flow Tools

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-12-1 15:29:11 | 显示全部楼层 |阅读模式
4.1 if 表达式
  作为最为人熟知的if.你肯定对这样的一些表达式不感到陌生:

>>> x = int(raw_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

  if 后面可以跟上一个或者多个分支,代码上表现为else或者elif.toturial菌的说明里面这样解释的:elif是else if的缩写...
  if ... elif ... elif ... 可以很好的作为类似C语言里面的switch ... case ... 的替代.
  

4.2. for 表达式
  同 C 或者 Pascal比较的话,Python中的for长的又略有不同.与前面两者不同的是(至于怎么不同,只有知道了才知道了,哎呀),Python里面的for表达式 'iterates over the items of any sequence',也就是说,任何可以 '迭代'的'东西'都是可以作为for表达式的对象的(a list or string).
  

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

原文这里给出了一个很好的栗子,解了我之前的一个疑惑,也是怪自己基础没有打牢固,不知道这样来用.
这里给出原文中的解释说明:
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>> 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. range()函数
  内建函数rang()用来生成一个整数构成的序列.
  range()有多种用法,
  range(stop)
  range(start, stop[, step])
  常用的是直接提供一个参数stop,比如

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




再比如,给出开始和结束:
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
又比如,给出开始,结束,又再给出步长:
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
负数哟哟,切克闹...
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

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

如果你有过C语言的学习经历,辣么你肯定对于break和continue不感到困惑和迷茫,简单来说,break就是用来终止当前层的循环(跳出当前一层的循环),continue则是用来进入当前循环的下一次.
欧耶,once more~
Python里面比较稀奇的是,对于循环(while, for)来说,还可以再跟上一个for循环.
  

4.5. pass Statements
  pass 就是什么也不做.给出几个常用的地方
  
  def foo():
  pass
  
  class Foo(object):
  pass
  
  if xxx:
  do something
  else:
  pass
  
  try:
  # if can
  do something
  except:
  # pass it
  pass
  简单的说一下,就是,有时候预定义一个函数,预定义一个类但是光是想到了原型骨架,细节部分尚为完善的时候,可以用一个pass来占位.这样Pthon编译的时候就可以通过,否则就会有语法错误.先用一个pass放在那里,后面再慢慢的完善.
  还有写地方必须要 '做些什么'的时候,但是又没有必要'做些什么',那么就也可以去做一点'什么也不做'的操作,比如说try的except里面
  

4.6. Defining Functions
  Python里面函数的定义需要用关键字def起头.函数名称中可以包含字母数字下划线,关于函数名字的问题,这个非常值得好好学习一番.
  def foo():
  do something
  函数名称需要定义的恰到好处,简洁明了,能看到函数就知道要做什么,想来也是极好的.
  
  函数支持别名,比如我定义了一个函数 def a_very_long_named_func():print 'hello';
  那么我同样也可以这样用
  f = a_very_long_named_func
  当我调用f()的时候,同样的也会打印 'hello'
  所有的函数都会有返回,默认没有return的时候,返回的就是None
  

4.7. More on Defining Functions

4.7.1. Default Argument Values
  为函数的参数指定一个默认值

i = 5
def f(arg=i):
print arg
i = 6
f()
这样做的意义在于,当没有传入参数的时候,默认值就会起作用,当有时候不必要去传入参数的时候,默认值同样也会起作用.
需要注意的是:
  Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:





def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)

  This will print





[1]
[1, 2]
[1, 2, 3]

  If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:





def f(a, L=None):
if L is None:
L = []
L.append(a)
return L

4.7.2. Keyword Arguments
  Python里面定义函数的时候,经常会看见诸如 def foo(request, *args, **kwargs)样子的函数
  这里需要说明的是*args是一个list,而**kwargs则是一个dict
  简单的一个栗子说明一下
  a, b, c, d = 1, 2, 3, 4
  e, f, g = 5, 6, 7
  def f(*args, **kwargs):
  print args, type(args)
  print kwargs, type(kwargs)
  f(a, b, c, d, e=e, f= f, g=g, h=a)
  #output
  [1, 2, 3, 4] list
  {'e': 5, 'f': 6, 'g': 7, 'h': 1} dict

4.7.5. Lambda Expressions
  Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:
  当一些函数简单到不需要专门的去定义一个函数的时候,可以用lambda临时的来一发,比如说这样

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

又比如:
f = lambda x, y: x + y # 冒号左边的是参数,右边的返回的值
f(1, 2) # 将会得到1和2的和3

4.7.6. Documentation Strings
  一份好的代码,往往不需要注释都清晰明了一目了然,但当项目代码变得复杂,高度的模块化了的时候,嵌套引用有时候又会让人看的云里雾里.所以适当的注释同样是有必要的.Python里面的有这么个东西 docstring,使用方法是用三引号给标记出来,python在适当的时候会自动的把这些东西展现出来,比如说,这样:

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print my_function.__doc__
Do nothing, but document it.
    No, really, it doesn't do anything.

4.8. Intermezzo: Coding Style

代码风格:每个语言都会有自己的代码风格,Python同样如此.关于代码风格,这里建议看一下PEP8 和PEP20
[pep8]http://legacy.python.org/dev/peps/pep-0008/
[pep20]http://legacy.python.org/dev/peps/pep-0020/

附上原文:


  • Use 4-space indentation, and no tabs.
      4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.


  • Wrap lines so that they don’t exceed 79 characters.
      This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.


  • Use blank lines to separate functions and classes, and larger blocks of code inside functions.


  • When possible, put comments on a line of their own.


  • Use docstrings.


  • Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).


  • Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).


  • Don’t use fancy encodings if your code is meant to be used in international environments. Plain ASCII works best in any case.



运维网声明 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-146000-1-1.html 上篇帖子: 使用python做简单的接口性能测试 下篇帖子: windows下如何快速优雅的使用python的科学计算库?
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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