thinkpython-Programming Basics

Source: Internet
Author: User
Tags aliases floor division python string format shallow copy string format tkinter tutorial qt designer

After reading some professional books, I have to admit that the books written by foreigners are more fascinating. The foreigner has the serious specialized work, but also has the very refined and the system structure consummation book can let you the quickest close new knowledge. This article is the reading notes of the "I python-how to" like a Computer scientist. The reader can download the PDF of the book and read it, and believe that you will benefit as much as I do.

After the first rough, I divided the book 19 chapters + Appendix into five parts:

Section1: Programming Basics

Section2: Data and storage

Section3: Object-oriented and class

Section4:gui

Section5:experience (Debugging&python algorithm analysis)

Section 1: Programming Basics

This article is the first part, the programming Foundation carries on the summary. In this section, learn and Master Python's syntax, variables, functions, and logical control statements in Python, Python's development specification.

1-CH1, interpreter & compiler Python is an interpreted language (most scripting languages are interpreted languages)

① a compiled language that compiles a written program into an executable binary code that can be executed directly on the machine. Fast execution, high efficiency, reliance on compilers, poor cross-platform performance, such as C + +

② interpreted language, the program translates a sentence, executes a sentence until the program is run over. Slow execution, low efficiency, dependency interpreter, Cross-platform, such as Java, Python

The program can be executed directly after the compiler compiles, and the interpreted language needs an interpretation environment after being interpreted. Java is a special language, it also needs to compile, but only compiled into bytecode, and then by the interpreter to explain the execution (JIT). \

2-CH1, debugging

Syntax Error, Runtime error (Exception), semantic error-if There is a semantic Error in your program, it would run successful Ly, but the problem is the program for you wrote are not the program for you wanted to write.

3-ch1, Experiental debugging

One of the most important skill you are acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of PR Ogramming.

Sherlock Holmes pointed out, "where you have eliminated the impossible, whatever remains, however improbable, must is the TR Uth. "

4-ch1, formal and natural language

Formal language are language that are designed by people for specific. For example, the notation this mathematicians use is a formal language this is particularly good at denoting relationships Among numbers and symbols.

Programming languages are formal languages that have been to express designed.

5-ch1, how to get help in Python

①, login python.org website, search inside enter to query such as print, the first record is the related usage of print

②, type help in the Interpreter (), enter the helper module, and type the Quit Exit Assist module

③, type help directly in the interpreter (' print ')

6-CH2, the compiler will tell you when the exact type of the value is uncertain. such as type (' my ') can also be used with isinstance (' my ', int)-obviously return false, and the second argument is a conjecture argument.

7-CH2, ZipCode = 02492, Anotherzipcode = 0x3826, the number that begins with 0 is the number of octal (octonary numbers system), and the hexadecimal number (hexadecimal) begins with 0x.

8, CH2, operator and arithmetic +-*/'//' * *

Note: There are two kinds of division in Python, one is traditional/, one is//, this division is called floor division, that is, the downward rounding

* * is a power operation

9, Ch3, module of two ways to import

Import Math

From math import */pi

The advantage of the latter is that the code becomes concise, the disadvantage is the name between the different modules, or the module and the custom variable name easily duplicate

10, CH3, debugging

When you write a script in a text editor, you encounter a problem with spaces and tabs. The best way to avoid these problems is to use only spaces (indent). Most text editors that recognize Python do so by default, but some are not.

11, CH4, case study, interface design, can skip

①, understanding the concept of refactoring, encapsulation, generalization (adding a formal parameter)

②, learn more or after Python has been in the open, then take a good look at this case Turtleworld, see how foreigners play python, very interesting, including the fifth chapter of the exercise

12, Ch5, type check

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >def factorial (n):
	if not isinstance (n, int): # if Type (n) <> int
		print ' factorial are only defined to Tegers ' return
		none
	elif N < 0:
		print ' factorial ' isn't defined for negative ' return
		none
	elif n = = 0: return
		0
	else: return
		n * factorial (n-1) </span></span></span></span ></span></span>
Type checking is required to improve the robustness of the program, in addition, you need to learn about exception handling.
13, ch7-iteration, small tip-print function

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >bruce = 5
print Bruce,
Alax = 6
print Alax
cvil = 7
Print cvil</span></span></ Span></span></span></span>
The effect of the output is:

5 6

7

The reason is ', ' after the first print statement to suppress the creation of new lines

Section2: Data and storage

14, ch8-string

① Negative Index string[-1] produces the last letter of a string

② string Slicing string[m:n] returns the character with index [M, N), String[m:n:i] returns the character with index (M, n) with interval I, such as String = ' string ', string[0:1] returns ' s '; [0:5:2] Return to SRN

③ string method, the book is very few, also need to refer to other learning materials for learning, reference 3

String.upper (), String.find (' a ')

④ file Read

Fin = open (' filename.txt ')

line = Fin.readline ()

line = Line.strip () #删除line中的空格及制表符

④python string format output http://www.cnblogs.com/vamei/archive/2013/03/12/2954938.html

15, ch10-for ... in statement

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >lista = [1,2,3,4,5] for
val in lista:
    val = 2;
Print lista</span></span></span></span>
The above code cannot change the value of Lista, if it is a value in read-only Lista, this method is very good, very safe, if you want to change the value of Lista, you need the index, that is, val[i] = 2.

16, Ch10-list method

append-append elements; extend-extension elements; sort-sort;

Know index Deletes with POPs, deletes and returns an element, deletes the last element if it is not provided, and if you know the element to be deleted, you can use the Remove,remove return value of none; You can delete more than one element, such as Del T[1:5, by using the Del and sliced indexes;

Split (), cutting a string into a list of words

Join (), in contrast to split, to merge word lists into strings

17, Ch10-list argument

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >def Add (t):
    t  = t + [m]    
    
def ADDV (t):
    t.append (MB)
    
def deletehead (t):
    t = t[1:]

def Deleteheadhead (t):
    del t[0]
    
t = [1,2,3]
Add (t)  #未能添加成功
print T 
ADDV (t) 
print T
Deletehead (t) #未能删除成功
print T
deleteheadhead (t)
print T</span></span></span ></span>
Distinguish Modify ListAnd generate a new listis important, as a parameter, if the list is modified within a function, the caller sees the change, and if a new list is generated within the function, the outer caller does not see the change. (using the online Python tutor to perform this process will be clearer)
In the list, most The built-in function modifies the argument and the return value is None, which is just the opposite of the string method.

Tips: Use replication to try to avoid aliases.

18, Ch12-tuple definition

A tuple is more like a list, but a tuple is immutable (string is also immutable) a tuple is a comma-separated list of values, although not necessary but usually enclosed in parentheses, such as T = ' a ', ' B ', ' C ' or t = {' A ', ' B ', ' C '} to generate a tuple with a single element, Must include the last comma, such as T = ' a ', or T = {' A ',} an alternative way to generate an array is to use the built-in function tuple, such as T = tuple () 19, Ch12-Elegant tuple A, B = B, and a so that the exchange of a, B is achieved, which is very excellent. The Jacobi group acts as a return value such as, Def Min_max (t): returns min (t), Max (t) minv, MAXV = Min_max (t) This is also very elegant collection *args variable length argument def printall (*args): P Rint args
T = (2, 1) divmod (*t) Example One, *args is a variable-length argument, in Example two, *t is called a collection of complements, that is, scatter, dividing the tuple into two digits into the function. 20, Ch12-list and tuple t = [(' A ', 1], (' B ', 2),  (' C ', 3),  (' d ', 4)] for letter, num in t:print, num in Python, there is a A built-in function zip that accepts two or more sequences and then zip them into a tuple list. Another built-in function enumerate returns the index value, and the value of each digit (P160) 21, Ch12-dictionary and tuple dictionaries have a method called items that returns a list of tuples d = {' A ': 0, ' B ': 1, ' C ': 2} t = D.items () pr int t gets [(' A ', 0), (' C ', 2), (' B ', 1)] by the same token, you can also use the list of tuples to initialize a new dictionary T = [(' a ', 0), (' C ', 2), (' B ', 1)] D = dict[t] Print D Get  {' A ': 0, ' C ': 2, ' B ': 1} zip and dict combinations produce a concise way to generate a dictionary: D = dict (Zip (' abc ', Range (3)) Dictionary method update also accepts a list of tuples, And as key-value pairs put them in an existing dictionary using tuples as the key of the dictionary is very common, such as Directory[last, the number 22, CH12-DSU mode decorate decoration, Build a tuple list by using one or more sort keys followed by elements from the sequence a sort sort   undecorate is similar to a list of elements 23, Ch11-dictionaries and lists by extracting sorted sequences, but more generally. In the list, the index must be an integer, in the dictionary, they can be any type to create a dictionary: ①, Direct assignment, ②, built-in function, ENG2SP = Dict (); in operator

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >ENG2SP = Dict ()
eng2sp[' one '] = 2 
print eng2sp
print ' One ' in ENG2SP
print 2 in eng2sp
print 2 in Eng2sp.values () </span></span></span></span>
Print results are true False, the first output statement is to find whether there is a key value of one, the last is to find whether there is a value of 2, pay attention to the difference. Reverse Search
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >def Reverselookup (d, v): for
    K in D:
        if d[k] = = V: return
            K
    raise valueerror</span></span& Gt;</span>
Of course, the above only returns the first value of V, if you want to return all the keys with a value of V, you return a list, in addition, the dictionary key values and values exchange, with the following code:
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >def Invertdict (d):
    inverse = Dict () for
    key in D:
        val = d[key]
        if val not int inverse:
            inverse[val ] = [key]
        else:
            inverse[val].append (key) return
    inverse</span></span></span>
The dictionary key value must be hash 24, Ch13-random number Ramdom () returns a float between [0.0, 1.0) randint (Low, high) returns an integer between [low and high] to select an element randomly from a sequence, You can use choice t = [1,2,3] Random.choice (t) 25, Ch13-random words
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >word = ' Love '
t = []
s = []
t.extend ([word]*2)
s.extend (word*2)
print t
print s
Print word*2
print [word]*2</span></span>
The output is: [' Love ', ' love ']
[' l ', ' o ', ' V ', ' e ', ' l ', ' o ', ' V ', ' e ']
Lovelove
[' Love ', ' love ']
The main idea here is to understand the function of the Extend function. different from Append. See Appendix 5 extend-Extension, extend parameter is always a list, it will add each element of list to the original list append-append, append parameter can be any data type, direct simple add to the original list 26, Ch13-Markov analysis Python supports multiline input-"" "Multiple" "" "Understanding the application of Markov analysis can be in operator to dictionary faster than the list 27, Ch14-file operation Open File Fout = open (filename, model) model can be defined as read R, write The W-read fout.write (str) format operator outputs the string in the manner defined by the format operator camels = "The num of camels is%d"%camels output the num of Camels is 42 file name and path import OS OS.GETCWD ()-Get current working directory
<span style= "FONT-SIZE:18PX;" >import OS

def Walk (dirname):
    for name in Os.listdir (dirname):
        path = Os.path.join (dirname, name)
        
        If Os.path.isfile (path):
            print path
        else:
            Walk (Path) </span>

Section3: Object-oriented and class

28, Ch15-python class and its definition

See http://blog.csdn.net/alywinxee/article/details/46005315

29, Ch15-deep copy and light copy

Aliases can cause programs to be less readable because changes in one place can accidentally affect another place. It's very difficult to track all the variables that reference the same object. Usually, replace the alias of the object with the method of copying the object import copy Example 1

<span style= "FONT-SIZE:18PX;" >P1 = Point ()
p1.x = 3.0
p1.y = 4.0

P2 = copy.copy (p1)

print P1 is p2  #False
print P1 = = p2
  
    > #False, the discrepancy with the preconceived
</span>
  
The default behavior of = = is the same as is, check first to see if the identity is the same, not the same value Example 2
<span style= "FONT-SIZE:18PX;" >box2 = copy.copy (box)
print box2 is box #False
print Box2.corner = = Box.corner #True
</span>
This is shallow copy (shallow copy) because only the object and its contained references are copied, but nested objects are not copiedDeep Copy (deepcopy) can not only copy objects, but also copy objects referenced by this object if the above is changed to Box2 = copy.deepcopy (box) Box2.corner = = Box.corner value is False, Box2 and box are completely irrelevant. Objects 30, CH17-Class and Method __init__ () initialization method __cmp__ () comparison size __str__ () is used to return a string expression of an object returning '%.2d:%.2d:%.2d '% (self . hour, Self.minute, Self.second) __add__ () operator overload, which overloads the + method type distribution P229 distribute different calculation methods according to the type of the parameter __radd__ () P229 right hand addition when a time object in the + operator When the right-hand side of the table appears, call this method 31, Ch18-class properties and Instance property class properties: Defined within a class but outside of a method, all instances share a Class attribute instance property: Within the initialization function, the instance attribute is associated to the specific instances property, each instance has its own instance property

Section4:gui

32. Ch19-thinter Case Study

Python offers several options for writing a graphical interface: including Wxpython, Tkinter, and Qt. To learn to use QT Designer interface design an Introduction to tkinter:http://effbot.org/tkinterbook/tkinter-index.htm

2014

Annual Xin Xing

Tkinter

Tutorial Second Edition

2014

Annual Xin Xing

Tkinter

Tutorial Second Edition 2014 Sinsing tkinter Tutorial Second Edition: http://wenku.baidu.com/view/ae1a1957a6c30c2259019e5b.html

section5:experience (Debugging&python algorithm analysis)

Appendix:

1. Key words

Global

2, is and = = Difference

In Python, there are variables of type frames and objects (see http://www.pythontutor.com/), and underlying data types (including strings) belong to the frames type, whereas lists, tuples, dictionaries, and so on are variables of type objects.

For variables of type frames, A is B also true if the value is equal

For variables of type objects, the return value of a is B, even if the value is equal, is false

The objects in Python contain three elements: ID, type, value
Where ID is used to uniquely identify an object, type identifies the object's types, and value is the object's values
is determines whether a object is a B object and is judged by ID
= = Determine whether the value of a object is equal to the value of the B object and is judged by value

However, if in the case of an alias, such as:

A = 1 b = a b = 2 The result is a = 1, b = 2

c = [1,2,3] D = c D[0] = 0 The result is c = d = [0,2,3], while C is D returns true

3, copy and Deepcopy


Reference documents:

1, Python variable name detection: http://ideasforjava.iteye.com/blog/649768

2. Division in Python: http://blog.csdn.net/sicofield/article/details/8613877

3, Python string module: Https://docs.python.org/2/library/string.html#string.Formatter

4. The study of string module in Python: http://www.cnblogs.com/rollenholt/archive/2011/11/25/2263722.html

5, Extend (extension) and append (append) the difference: http://justjavac.iteye.com/blog/1827915

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.