DUST

Do the things I want to do

Python 笔记(2) -- Control Flow

 

[Src: Python 2.5 Document]

 

1. if-statement

与C/C++不同的是,Python中 if 或 elif 要以 : 结尾

 

Code

 

2. for-statement

   iterates over the items of any sequence(a list or a string)

 

Code

 

   若要修改序列中的内容,就只能在序列的副本上遍历。这里只能修改list的内容

 

Code

 

3. range()

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

   b) range(5, 10)           ==> [5, 6, 7, 8, 9]

   c) range(-10, -100, -30)  ==> [-10, -40, -70]

 

4. else clause

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.

即,当循环正常结束后,才会走到else语句中;如果循环被break掉,则跳过else

 

Code

 

5. pass-statement

    空语句,语法要求

 

6. Defining functions

    def func_name(parameter1, parameter2,...)

    函数参数的解析顺序:local symbol table -> global symbol table -> built-in symbol table

    通常情况下只能在函数中访问global的变量,但无法修改其值。除非用global显式声明

    a) Default Argument Values

        从左到右的顺序,如果某个参数设有默认值,则其后的所有参数都必须设有默认值,与C++类似

 

Code

        Default Value只会被赋值一次,因此可以对同一个函数,后续的调用会使用到前次调用的结果

 

Code

     消除此种影响的方法:

 

Code

 

    b) Keyword Arguments

        允许以 "keyword = argument" 的方式传参。此时,传参的顺序不必遵守定义的顺序。No argument may receive a value more than once

        注意:如果未以这种方式传参,则按照从左到右顺序赋值。一旦某个参数以keyword方式传参,则其后所有参数也必须采用此种方法

 

Code

 

     **parameter: 接受一个dictionary(包含一组keyword arguments)

     *parameter:  the positional arguments beyond the formal parameter list。不能接受keyword arguments参数

     如果两者一起使用,则*parameter必须出现在**parameter之前

 

Code

 

     c) Arbitrary Argument Lists

       

Code

 

     d) Unpacking Argument Lists

        如果参数已经存于list或tuple中,则用*来展开参数

        如果参数存于dictionary中,则用**

 

Code

 

     e) Lambda Forms

         (与函数编程语言类似的功能?)像个函数

 

Code

posted on 2008-09-03 19:00  should  阅读(277)  评论(0编辑  收藏  举报

导航