Python学习总结二

来源:互联网 发布:微谱数据库 编辑:程序博客网 时间:2024/05/05 10:35
 More Control Flow Tools   控制流动语句
        1、if ... elif ... elif ... 
        2、for语句:
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print(x, len(x))
...
cat 3
window 6
defenestrate 12
        3、It is not safe to modify the sequence being iterated over in the loop 。在循环迭代中修改序列是不安全的。(只能用于可变序列类型,如list)。如果需要修改迭代的list,先复制一个copy。需要是slice标记法,会很方便。a[:]
>>> for x in a[:]: # make a slice copy of the entire list
...    if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
        4、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。如果修改迭代一个有序数字。使用range(),产生数学过程。
        range(10),从0开始到9,总共十个数字(默认从0开始)
        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(5,10)  5,6,7,8,9                
        range(5,10,3)   5,8
range(5, 10)
   5 through 9

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

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

        5、In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.
        6、 break and continue Statements, and else Clauses on Loops
        7、pass Statements
Defining Functions定义函数
        1、
Ctrl + a - Jump to the start of the line        Ctrl + b - Move back a char        Ctrl + c - Terminate the command         Ctrl + d - Delete from under the cursor        Ctrl + e - Jump to the end of the line        Ctrl + f - Move forward a char        Ctrl + k - Delete to EOL        Ctrl + l - Clear the screen         Ctrl + r - Search the history backwards          Ctrl + R - Search the history backwards with multi occurrence        Ctrl + z - Suspend/Stop the command
        2、清理屏幕:
import os
i=os.system('cls')

def clear():
        for i in range(60):
                print()
        3、def定义函数
>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
        4、每个函数都有返回值,即使没有return语句。则返回None
>>> fib(0)
>>> print(fib(0))
None
        5、More on Defining Functions  更多定义函数的方法。It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.
        6、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:
        重要警告:默认值值计算一次。如果默认值是一个可变的值如list,dictionary,class的实例。将会随着随后的调用而累计起来
>>> def f(a, L=[]):   #L是一个List
        L.append(a)
        return L

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>>
        如果你不想在之后的调用中累计起来的话,可以设置为None。
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

print(n, end=' ')  表示后面不更默认的换行符,而只是接上'  '空格字符串
        7、Keyword Arguments。Functions can also be called using keyword arguments of the form keyword = value. For instance, the following function:   函数能使用关键参数的形式   keyword=value    
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

        voltage是关键参数。其它的参数都是默认值。
could be called in any of the following ways:
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')

but the following calls would all be invalid:
parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument following keyword
parrot(110, voltage=220)     # duplicate value for argument
parrot(actor='John Cleese')  # unknown keyword

下面这种情况是同时定义了两次a,重复定义
>>> def function(a):
        pass

>>> function(0, a=0)
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    function(0, a=0)
TypeError: function() got multiple values for keyword argument 'a'
>>>
        8、When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. 当一个参数的没错是**name,表示接受一个字典,包含了关键字keys,查找name[keys].
        This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list.如果是*name,接受一个数组(元组)。
        (*name must occur before **name)   *name必须在**name之前发生。
>>> def cheeseshop(kind, *arguments, **keywords):
        print("-- Do you have any", kind, "?")
        print("-- I'm sorry, we're all out of", kind)
        for arg in arguments:    #arguments是元组
                print(arg)
        print("-"*40)
        keys = sorted(keywords.keys())    #keywords是一个词典,keys关键字
        for kw in keys:
                print(kw, ":", keywords[kw])

               
>>> cheeseshop("limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
-- Do you have any limburger ?
-- I'm sorry, we're all out of limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch


        enclosed包括与否没有圆括号,方括号,只靠缩进(indentation)来确定是否包含在内

         for arg in arguments:    #arguments是元组
                print(arg)
        print("-"*40)
和下面的有区别。print包含在for循环语句与否
         for arg in arguments:    #arguments是元组
                print(arg)
                print("-"*40)
       
        9、Arbitrary Argument Lists
>>> def concat(*args, sep="/"):
...    return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

原创粉丝点击