Python Self-study notes

Source: Internet
Author: User
Tags aliases pow

Python self-study notes

  • Python Self-study notes
    • 1. Output
    • 2. Enter
    • 3. Piecemeal
    • 4. Data structure
      • 4.1 List analogy to an array in Java
      • 4.2 Tuple Ganso
    • 5. Conditional Judgment and circulation
      • 5.1 Article judgment
      • 5.2 Cycles
    • 6. Using Dict and set
      • 6.1 Dict
      • 6.2 Set
    • 7. Use of functions
      • 7.1 function returns multiple values while accepting multiple values
      • 7.2 Default values for function parameters
      • 7.3 Functions for variable parameters
      • 7.4 parameter names with variable number of arguments
      • 7.5 Combination of parameter types
    • 8. About function recursion
    • Advanced Features of 9.python
      • 9.1 Slices
      • 9.2 Traversal
      • 9.3 List Builder
        • How to use 9.3.1?
        • Where is 9.3.2 used?
      • 9.4 Generators
    • 10. Functional programming
      • 10.1 Higher order functions
      • 10.2 map () and reduce () functions
        • 10.2.1 Lambda function
        • 10.2.2 Practice
      • 10.3 Filter
      • 10.4 Sort
    • 11 Advanced functions
      • 11.1 Anonymous functions
      • 11.2 Decorators
    • 12 Modules
      • 12.1 Using Modules
        • 12.1.1 is used directly at the command line
        • 12.1.2 importing modules using aliases
      • 12.2 Search Path of the module
1. Output

printSeparate multiple output strings with commas, or use "+" instead of ","

print "李帅",“王子轩”
2. Enter
name = raw_input()#有提示的输入:name = raw_input(‘please enter your name: ‘)print ‘hello,‘, name
3. Piecemeal
    • If there are many characters in the string that need to be escaped, you need to add a lot of \, in order to simplify, Python also allows the use of R "to express" internal strings are not escaped by default
    • If there is a lot of line wrapping inside the string, it is not good to read it in a line, and in order to simplify, Python allows the format of "' ..." to represent multiple lines of content
    • The first line of comments is to tell the Linux/os x system that this is a python executable, and the Windows system ignores this comment; the second line of comments is to tell the Python interpreter to read the source code according to UTF-8 encoding, otherwise The Chinese output you write in the source code may be garbled.
#!/usr/bin/env python# -*- coding: utf-8 -*-+
4. Data Structure 4.1 list analogy to an array in Java
classmates = [‘Michael‘, ‘Bob‘, ‘Tracy‘]

Use an index to access the elements of each location in the list, remembering that the index starts at 0:
Classmates[0]
If you want to take the last element, in addition to calculating the index location, you can also use 1 to index, get the last element directly:
CLASSMATES[-1]
The list is a mutable, ordered table, so you can append an element to the end of the list:
Classmates.append (' Adam ')
You can also insert an element into a specified position, such as a position with an index number of 1
python
classmates.insert(1, ‘Jack‘)
p = [‘asp‘, ‘php‘]
s = [‘python‘, ‘java‘, p, ‘scheme‘]

To get ' php ' can write p[1] or s[2][1], so s can be regarded as a two-dimensional array, similar to three-dimensional, four-dimension ... arrays, but rarely used.

4.2 Tuple Ganso

Tuple and list are very similar, but a tuple cannot be modified once initialized

classmates = (‘Michael‘, ‘Bob‘, ‘Tracy‘)
5. Conditional judgment and cyclic 5.1-piece judgment
if <条件判断1>:    <执行1>elif <条件判断2>:    <执行2>elif <条件判断3>:    <执行3>else:    <执行4>
5.2 Cycles

There are two types of Python loops

    • One is the for...in loop, which sequentially iterates through each element in the list or tuple
names = [‘Michael‘, ‘Bob‘, ‘Tracy‘]for name in names:    print name
    • The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting the loop when the condition is not satisfied. For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:
sum = 0n = 99while n > 0:    sum = sum + n    n = n - 2print sum
6. Use Dict and set6.1 dict

Dict support, Dict full name dictionary, also known as map in other languages

>>> d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}>>> d[‘Michael‘]95

Dict Search Faster reason: given a name, such as ' Michael ', Dict can directly calculate Michael's corresponding storage Score "page number", that is, 95 of the memory address of the number stored, directly out, so very fast.

Compared with list, Dict has the following features:

    • Finding and inserting is extremely fast, does not increase with the increase of key, it takes a lot of memory, and memory is wasted.
      And the list is the opposite:
    • The time to find and insert increases as the element increases;
      Small footprint and little wasted memory.
      So, Dict is a way of exchanging space for time.
6.2 Set

Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.

To create a set, you need to provide a list as the input collection:
s = Set ([1, 2, 3])

7. Functions using the 7.1 function returns multiple values while accepting multiple values

Functions in Python can return multiple values directly. It's actually a fake, it's returned in the form of a tuple.

__author__ = ‘shuai.li‘import mathdef distance(x, y, step, angle=45):    nx = x + step * math.cos(angle)    ny = y + step * math.sin(angle)    return nx, ny# main functionif __name__ == "__main__":    nx, ny = distance(5, 10, 1)    print nx, ny>>>C:\pythonTest>python function.py>>>4.55192638387 10.8939966636

The following output can be seen as actually a tuple type

if __name__ == "__main__":    r = distance(5, 10, 1)    print r>>>C:\pythonTest>python function.py>>>(5.52532198881773, 10.850903524534118)
7.2 Default values for function parameters

Pit of Function default value

def add_end(L=[]):    L.append(‘END‘)    return L>>> add_end()[‘END‘]但是,再次调用add_end()时,结果就不对了:>>> add_end()[‘END‘, ‘END‘]>>> add_end()[‘END‘, ‘END‘, ‘END‘]

The reason is that L actually in Python is a variable, it points to the object [], when used to change the value of L, then its point to change the content, so the default value of the function parameter is best an immutable object

7.3 Functions for variable parameters

Add * to the parameter to change the function parameter to a variable parameter

def cal(*numbers):    sum = 0    for num in numbers:        sum = sum + math.pow(num, 2)    return sum# main functionif __name__ == "__main__":    r = cal(1, 2)    print r    r1 = cal(1, 2, 3)    print r1>>> C:\pythonTest>python function.py>>> 5.0>>> 14.0

But I was a tuple or list can not let me put the object of the inside one after another. No, Python provides a workaround that is to give Python the rest of the "*" Operation directly in front of your tuple or list.

def cal(*numbers):    sum = 0    for num in numbers:        sum += math.pow(num, 2)    return sum# main functionif __name__ == "__main__":    r = (1, 2)    print cal(*r)>>> C:\pythonTest>python function.py>>> 5.0
7.4 parameter names with variable number of arguments

* * This allows you to pass in 0 or more parameters with parameter names, used in cases with required parameters and non-mandatory parameters, and variable parameter functions like directly passing key value pairs in parameters, or without passing parameters

def student(name, age, **city):    print name, age, city# main functionif __name__ == "__main__":    city = {"city": "beijing", "street": "suzhoujie"}    student("lishuai", 12, city="beijing", street="suzhoujie")>>>C:\pythonTest>python function.py>>>lishuai 12 {‘city‘: ‘beijing‘, ‘street‘: ‘suzhoujie‘}

Of course, the parameters passed in can be directly dict, so that they can be passed directly as mutable parameters.

def student(name, age, **city):    print name, age, city[‘city‘], city[‘street‘]# main functionif __name__ == "__main__":    city = {"city": "beijing", "street": "suzhoujie"}    student("lishuai", 12, **city)
7.5 Combination of parameter types

Defining functions in Python can be done with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of the parameters definition must be: required, default, variable, and keyword parameters. 4

!!! When all of these four types are available, you can pass in the tuple and dict directly. Note that at this point the tuple automatically fills in the preceding required fields so, for any function, it can be called by a Func-like (*args, **kw), regardless of how its arguments are defined.

def func(a, b, c=0, *args, **kw):    print ‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw>>> args = (1, 2, 3, 4)>>> kw = {‘x‘: 99}>>> func(*args, **kw)a = 1 b = 2 c = 3 args = (4,) kw = {‘x‘: 99}

Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use idiomatic usage.???
After trying, it is impossible to remove the "" and "*" before the parameter.

8. About function recursion

Beware of stack overflow when recursion. The call to the function is implemented through the data structure of the stack, and each time a function call is entered, the stack is incremented by one layer, and the stack is reduced by one layer whenever the function returns. The stack inside the computed memory is limited.
The method of solving recursive call stack overflow is optimized by tail recursion, in fact, each time the function recursive is called, the parameters passed in are already calculated in advance, so the stack layer is not stacked.

Advanced features of 9.python 9.1 slices
    • Slice is equivalent to taking one piece directly
    • -1 can represent the last object
    • [] The left side of the object in the list is also on the left, if the order is reversed, you will get an empty list
__author__ = ‘shuai.li‘if __name__ == "__main__":    l = ["lishuai", "wangwang", "lili", "shuai"]    print l[0:3]    print l[-1]    print l[-3:-1]    print l[-1:-3]    print l[-3:]    print l[::2]>>>C:\pythonTest>python special.py[‘lishuai‘, ‘wangwang‘, ‘lili‘]shuai[‘wangwang‘, ‘lili‘][][‘wangwang‘, ‘lili‘, ‘shuai‘][‘lishuai‘, ‘lili‘]   #特别注意这个的用法,每两个取一个
9.2 Traversal
__author__ = ‘shuai.li‘if __name__ == "__main__":    student = {"name": "lishuai", "age": 12}    for k, v in student.items():        print k+":"+str(v)C:\pythonTest>python  iteration.pyage:12name:lishuai
9.3 List Builder 9.3.1 How to use it?

The list generation, which is the comprehensions, is a very simple and powerful build of Python built-in that can be used to create lists.
Write how to generate each item (the contents of each item), followed by a few (conditions for each item), from point to line

__author__ = ‘shuai.li‘if __name__ == "__main__":    print [x + x * x for x in range(0,10,2)]>>>C:\pythonTest>python listGenerate.py>>>[0, 6, 20, 42, 72]

You can add an if condition after the for loop.

if __name__ == "__main__":    print [x for x in range(0, 50) if x % 3 == 0 if x % 4 == 0 ]

Note If there is an if condition later. The step is ignored by the program.

if __name__ == "__main__":    print [x for x in range(0, 50, 2) if x % 3 == 0 if x % 4 == 0 ]>>>C:\pythonTest>python listGenerate.py>>>[0, 12, 24, 36, 48]

can also be multi-layer cycle

if __name__ == "__main__":    print [m+n for m in ‘xyz‘ for n in ‘abc‘ ]C:\pythonTest>python listGenerate.py[‘xa‘, ‘xb‘, ‘xc‘, ‘ya‘, ‘yb‘, ‘yc‘, ‘za‘, ‘zb‘, ‘zc‘]

The preceding conditions can also be written in the form of a function

 l = [‘HELLO‘, ‘Fuck‘, ‘yoU‘]    print [s.lower() for s in l]
Where is 9.3.2 used?

A long list needs to be listed, and each object is similar.
For example: List all files and directories in the current directory

import osif __name__ == "__main__":    
9.4 Generators

The benefit of the generator is that the edge generates edge calculations so that it does not take up much space as the list Builder does, especially when a large list is useful.
The way to do this is to change the list-generated [] to () and create a generator:
However, we can print out each element of the list generator directly, but we cannot print out the generator's elements directly, we need to use the next () function, and we can iterate over the object using the For loop.

There is another way to do this: include the yield keyword
The hardest thing to understand is that generator is not the same as the execution of a function. The function is executed sequentially, the return statement is encountered, or the last line function statement is returned. The function that becomes generator, executes at each call to next (), encounters a yield statement return, and executes again from the yield statement that was last returned.
The effect of yield is to turn a function into a generator, the function with yield is no longer a normal function, the Python interpreter treats it as a generator, and the Call to FAB (5) does not execute the FAB function, but instead returns a Iterable Object! When the For loop executes, each loop executes the code inside the FAB function, and when it executes to yield B, the FAB function returns an iteration value, and the next iteration, the code proceeds from the next statement of Yield B, and the local variable of the function looks exactly the same as before the last break, so the function Continue execution until yield is encountered again.

A function with yield is a generator that can traverse an element using the for in iterate, or use Function.next () to traverse an element

The following is a generator that generates an integer multiplier of 3

__author__ = ‘shuai.li‘# coding:utf-8# 一个返回3的整数倍的生成器def odd(n):    a = 0    while n > 0:        a += 3        n -= 1        yield aif __name__ == "__main__":    for a in odd(5):        print ainput:>>> C:\pythonTest>python generator.py3691215
10. Functional programming

Functional Programming is a very high degree of abstraction of the programming paradigm, the purely functional programming language functions are not variable, so any function, as long as the input is determined, the output is OK, this pure function we call no side effects. In the case of programming languages that allow the use of variables, because of the variable state inside the function, the same input may get different output, so this function has side effects.

One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned!

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

10.1 Higher order functions

Functions can be assigned to variables like variables

if __name__ == "__main__":    f = abs    print f(-1)

The above program shows that F is now pointing to the ABS function itself

So what is the function name? The function name is actually a variable pointing to the function! For the ABS () function, it is perfectly possible to think of ABS as a variable, which points to a function that calculates the absolute value!

Incoming function

def add(a, b, f):    return f(a) + f(b)if __name__ == "__main__":    print add(5, -10, abs)

Writing higher-order functions allows the parameters of a function to receive other functions.

10.2 map () and reduce () functions

The map function is to pass in one function to perform the same processing for each element in the other object passed in. Reduce () is the first two elements of a subsequent object, and then the composition of an element then works with the third element until all the elements have been processed.
Converts a number in a list to a string:

Simple use of Map

if __name__ == "__main__":    print map(str, [1, 2, 3, 4, 5])>>> C:\pythonTest>python mapAndreduce.py>>> [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]

The effect of reduce is:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

The conversion string is of type int:

# str转换为int的函数def strtoint(s):    # 首先要把str判断下是否全是数字类型的字符,不做    # 一个个字符转换为数字,然后数字列表    l = map(int, s)    # 数字列表变成int    return reduce(numtoint, l)def numtoint(a, b):    return 10 * a + bif __name__ == "__main__":    print strtoint("356546")    print isinstance(strtoint("356546"),int)>>> C:\pythonTest>python mapAndreduce.py>>> 356546>>> True
10.2.1 Lambda function

Can be used to write single-line functions, so that when a simple logic processing need not write a function to deal with, directly with the lambda to handle
This can be said to simplify the above function:

# str转换为int的函数def strtoint(s):    # 首先要把str判断下是否全是数字类型的字符,不做    # 一个个字符转换为数字,然后数字列表    l = map(int, s)    # 数字列表变成int    return reduce(lambda x, y: 10 * x + y, l)if __name__ == "__main__":    print strtoint("356546")    print isinstance(strtoint("356546"), int)
10.2.2 Practice

1. Using the map () function, the user input of the non-standard English name, the first letter capitalized, other lowercase canonical name. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart '].

if __name__ == "__main__":    print map(lambda s:s[0].upper()+s[1:].lower(),[‘adam‘, ‘LISA‘, ‘barT‘])>>> C:\pythonTest>python exersize1.py>>> [‘Adam‘, ‘Lisa‘, ‘Bart‘]

The sum () function provided by 2.Python can accept a list and sum, write a prod () function that accepts a list and uses the reduce () to calculate the product.

def prod(l):    if not isinstance(l, list):        return "错误的输入参数类型"    else:        return reduce(lambda x, y: x + y, l)if __name__ == "__main__":    print prod([23,34,1,2])
10.3 Filter

Like map (), filter () also receives a function and a sequence. When different from map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

if __name__ == "__main__":    print filter(lambda x: x % 2 == 0, range(1, 100))
10.4 Sort

Generally, for two elements x and Y, if you think X < Y, then return-1, if you think x = = y, then return 0, if you think x > Y, then return 1, so that the sorting algorithm does not care about the specific comparison process, but based on the results of the comparison directly sorted. So we need to rewrite the sorting algorithm.

Functions in reverse order

def revert(x, y):    if x > y:        return -1    elif x == y:        return 0    else:        return 1if __name__ == "__main__":    print sorted([34, 67, 89, 32, 56, 23, 12, 567, 3], revert)>>> C:\pythonTest>python  filter.py>>> [567, 89, 67, 56, 34, 32, 23, 12, 3]
11 Advanced Functions 11.1 anonymous functions

What if you do not need to sum immediately, but in the later code, as necessary to calculate what to do? You can return the SUM function without returning the result of the summation!

def lazy_sum(*args):    def sum():        ax = 0        for n in args:            ax = ax + n        return ax    return sum

When we call Lazy_sum (), we return the SUM function instead of summing the result:

>>> f = lazy_sum(1, 3, 5, 7, 9)>>> f<function sum at 0x10452f668>

The result of summing is actually computed when the function f is called:

>>> f()25

In this example, we define the function sum in the function lazy_sum, and the inner function sum can refer to the arguments and local variables of the external function lazy_sum, and when Lazy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, which is called The program structure of the "Closure (Closure)" has great power.

Note again that when we call Lazy_sum (), each call returns a new function, even if the same parameter is passed in:

>>> f1 = lazy_sum(1, 3, 5, 7, 9)>>> f2 = lazy_sum(1, 3, 5, 7, 9)>>> f1==f2False

The invocation results of F1 () and F2 () do not affect each other.

11.2 Decorators

My own understanding:
followed by a function, the following function is given to the function after the @ as a parameter.
The adorner has an intrinsic function that returns the function after it has been processed and returns the adorner.

def log(func):    def wrapper(*args, **kw):        print ‘call %s():‘ % func.__name__        return func(*args, **kw)    return wrapper@logdef sum():    print "lishuai"if __name__ == "__main__":    sum()
12 Modules

In Python, a. py file is called a module
To avoid module name collisions, Python introduces a way to organize modules by directory, called packages.
1) Why should I have modules and packages?
Easy to organize your code while avoiding conflicts.

2) How to represent a package?
Under each package directory there will be an init. py file, which must exist, otherwise Python will treat this directory as a normal directory instead of a package. The init. PY can be an empty file, or it can have Python code because the init. PY is itself a module, and its module name is MyCompany.

3) How to determine the name of the module?
Name of package name + module

12.1 Using Modules12.1.1 is used directly at the command line
if __name__==‘__main__‘:    test()当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。
12.1.2 importing modules using aliases

The advantage is that the library can be selected according to the actual

try:    import cStringIO as StringIOexcept ImportError: # 导入失败会捕获到ImportError    import StringIO

In a module, we may define many functions and variables, but some functions and variables we want to use for others, some functions and variables we want to use only within the module. In Python, this is done through the _ prefix.

Normal functions and variable names are public and can be directly referenced, for example: ABC,X123,PI, etc.;

Such variables like xxx are special variables, can be directly referenced, but for special purposes, such as the above author,name is a special variable, hello module definition of the document comments can also be used with special variables Doc access, our own variables are generally not used in this variable name;

functions or variables such as _xxx and XXX are nonpublic (private) and should not be referenced directly, such as _ABC,ABC, etc.;

The reason why we say thatprivate functions and variables "should not be" directly referenced, rather than "cannot" be directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, however, The private function or variable should not be referenced from the programming habit.

12.2 Search Path of the module

By default, the Python interpreter searches the current directory, all installed built-in modules, and third-party modules, and the search path is stored in the PATH variable of the SYS module:

If we want to add our own search directory, there are two ways:

One is to modify the Sys.path directly and add the directories to be searched:

>>> import sys>>> sys.path.append(‘/Users/michael/my_py_scripts‘)

This method is modified at run time and is invalidated after the run is finished.

The second method is to set the environment variable Pythonpath, and the contents of the environment variable are automatically added to the module search path. Settings are similar to setting the PATH environment variable. Note that you only need to add your own search path, and Python's own search path is unaffected.

Python Self-study notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.