Python Tutorial 学习(四)--More Control Flow Tools

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(startstop[, 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.

posted @ 2014-12-02 22:07  Mx.Hu  阅读(368)  评论(0编辑  收藏  举报