"Dive into Python" Chapter 2 and Chapter 3 notes

Source: Internet
Author: User

Example 2.1. odbchelper.py

def buildconnectionstring (params): "" "    Build a connection string from a dictionary    Returns string.    " " Return ";". Join (["%s=%s"% (k, v) for K, V in Params.items ()]) if __name__ = = "__main__":    myparams = {"Server": "Mpilgrim",     "Da Tabase ":" Master ",     " UID ":" sa ",     " pwd ":" Secret "    }    Print buildconnectionstring (myparams)

Output from odbchelper.py:

Pwd=secret;database=master;uid=sa;server=mpilgrim

1. Function declaration

The function in Python does not need to specify the data type of the return value, and does not even need to specify whether there is a return value. In fact, each Python function returns a value: If the function executes a return statement, it returns the specified value, otherwise it will return none (a null value for Python).

2. Documentation functions

You can document a Python function by giving a doc string (the document string).

def buildconnectionstring (params): "" "    Build a connection string from a dictionary    Returns string." "

Sanchong quotation marks represent a multiline string. Everything between the start and end quotes is treated as part of a single string, including a hard carriage return and other quote characters. Everything in the Sanchong quotes is the doc string for this function, which is used to illustrate what the function can do. If a doc string exists, it must be the first content to be defined by a function (that is, the first content after the colon).

3. Objects of all Things

In Python everything is an object, and almost everything has attributes (what it looks like) and methods (what it does). Everything is an object that can be interpreted emotionally as: Everything can be assigned to a variable or passed as a parameter to a function.

4. Test module

All Python modules are objects and have a built-in property of __name__. The value of the __name__ of a module depends on how you apply the module:

If the import module, then the value of __name__ is usually the file name of the module, without the path and file extension.

>>>import odbchelper>>>odbchelper.__name__ ' Odbchelper '

If you run the module directly, the value of __name__ will be a special default value (that is, the default value), __main__.

You can use this feature to design a test suite inside a module:

If __name__== "__main__":

When the module is run directly, the value of the __name__ is __main__, so the test suite executes. When importing a module, the value of __name__ is something else, so the test suite is ignored. This makes it much easier to develop and debug a new module before it is integrated into a large program.

5. Dictionary (Dictionary)

>>>d = {"Server": "Mpilgrim", "Database": "Master"}       (1) >>>d {' Server ': ' Mpilgrim ', ' Database ': ' Master '}>>>d[' "Server"                                         (2) ' Mpilgrim ' >>>d["database"] ' master ' >>>d{"Mpilgrim"}                                       (3) Traceback (innermost last):  File "<interractive input>", line 1, in? keyerror:mpilgrim>>>d["datebase"] = "Pubs"                              (4)    >>>d{' server ': ' Mpilgrim ', ' Database ': ' Pubs '}                >>>d["uid"] = "sa"                                     (5) >>>d{' server ': ' Mpilgrim ', ' uid ': ' sa ', ' database ': ' pubs '}

(1) Create a new dictionary that has two elements and assigns it to the variable d. Each element is a key-value pair; the entire element set is enclosed in curly braces.

(2) ' Server ' is a key, and its associated value is referenced by d["Server", for ' Mpilgrim '.

(3) A key can be used to reference its value, but it cannot be obtained by a value.

(4) There can be no duplicate key in a dictionary. Assigning a value to an existing key overrides the original value.

(5) 1, at any time can be added to the new key-value. 2, the dictionary is disorderly.

The dictionary key is case-sensitive (that is, case-sensitive).

Dictionary is more than just a string to store. Its value can be any data type, including strings, integers, objects, and even other dictionary. In a single dictionary, its values do not need to be all of the same data type and can be mixed and matched as needed. Dictionary's key is much stricter.

Del Dictionary[key] Use key to remove independent elements from a dictionary.

Dictionary.clear () Clears all elements in the dictionary.

6. Lists (list)

The elements in the list are ordered and do not have to be unique.

Append (append) accepts a parameter (this parameter can be any data type) and is simply appended to the list trailer. The Extend (extension) takes a parameter, which is always a list, and adds each element of the list to the original list.

Insert inserts a single element into the list. The numeric parameter is the index of the insertion point.

Index finds the first occurrence of a value in the list and returns the index value. If no value is found in the list, Python throws an exception.

To test whether a value is in the list, use in. If the value exists, it returns true, otherwise false is returned. The first letter of true and false must be capitalized.

Remove removes the first occurrence of a value from the list. If the value is not found, Python also returns an exception.

Pop deletes the last element of the list, and then returns the value of the deleted element.

The list can be concatenated with the + operator. List = list + otherlist is equivalent to list. Extend (otherlist).

Li + = [' Both '] is equivalent to li.extend ([' both ']).

The * operator can act as a duplicate in the list. Li = Li * 3 connects the three lists into one.

7, tuple (tuple)

A tuple is a list that cannot be changed. Once a tuple has been created, it cannot be changed in any way.

A tuple is defined in the same way as a list, but the entire set of elements is surrounded by parentheses, not square brackets.

The elements of a tuple are sorted in the order defined by the list.

A tuple has no method, but you can use in to see if an element exists in a tuple.

Benefits of using tuple:

    • A tuple operates faster than a list, if a constant set of values is defined, and the only thing to do with it is to continually traverse it, you should use tuple instead of list.
    • You can make your code more secure if you write-protect the data that you do not need to modify.
    • A tuple can be used as key in dictionary, but list is not. The Dictionary key must be immutable.
    • A tuple can be used in string formatting.

8. Variable declaration

When a command is split into multiple rows with a continuation character ("\"), subsequent rows can be indented in any way.

Assign multiple values at once

>>> v = (' A ', ' B ', ' E ') >>> (z/y) = v>>> x ' A ' >>>y ' b>>>z ' e '

V is a tuple of ternary, and (x, Y, z) is a tuple of three variables. Assigning a tuple to another tuple assigns each value of V to each variable in order.

Continuous value Assignment

>>>range (7) [0,1,2,3,4,5,6]>>> (monday,tuesday,wednesday,thursday,friday,saturday,sunday) = Range (7) >>>monday0>>>tuesday1>>>sunday6

The built-in range function returns a list of elements as integers.

9. Formatting strings

Formatting of strings

>>> uid = "sa" >>> pwd = "se cret" >>> print pwd + "IsNot agood passwor D for" + UID       (1) Sec RET isn't Agoodpasswo Rd for sa>>> print '%s is nota good passw ord for%s '% (PW D,uid) (2) Secretis not agood p Asswo Rd for sa>>> usercou NT = 6>>> print "Users con nected:%d"% (use Rcoun t,)         (3) (4) Users Conn ected:6>>> print "Users con nected:" + Usercoun t               (5) Traceback (innermost last): File "<i nteract ive INP Ut> ", line 1, in? Typeerror:cannot concatenate ' str ' and ' int ' objects

(1) Connect by connection operator "+"

(2) Implementing a connection through string formatting

(3) (UserCount,) is a tuple that contains only one element. When defining a list,tuple,dictionary, you can always follow the last element followed by a comma, but a comma is required when defining a tuple that contains only one element. If you omit commas, Python will not know whether (UserCount) is a tuple with only one element or a value of variable UserCount.

(4) String formatting the integer can be processed by replacing%s with%d.

(5) Attempting to concatenate a string with a non-string will throw an exception. String connections can only work if each of the connected characters is a string.

Formatting of numeric values

>>> print "Today's stock price:%f"%50.4625   (1) 50.462500>>> print "Today's stock price:%.2f"%50.4 625 (2) 50.46>>> print "Change since yesterday:%+.2f"%1.5 (3) +1.50

(1) The%f format symbol option corresponds to a decimal floating-point number, which prints 6 decimal places when no precision is specified.

(2) using the%f format option with the ". 2" correction modifier will print only 2 decimal places.

(3) Add + modifier to display a positive or negative sign before the value.

10. Map List

Maps a list to another list by applying a function to each element in the list

>>> Li = [1, 9,8, 4]>>> [elem*2 for Elem in Li]        (1) [2,, 8]>>> Li                             (2) [1, 9, 8, 4] >>> Li = [elem*2 for Elem in Li]  (3) >>> li[2, 18, 16, 8]

(1) Li is a list that will be mapped. Python loops through each element in the LI. Do the following for each element: first temporarily assigns its value to the variable elem, then Python applies the function elem*2 for the calculation, and finally appends the result to the list to be returned.

(2) Parsing the list does not change the original list.

(3) It is safe to assign the parse result of a list to the variable to which it is mapped.

Keys, values, and items functions

>>> params = {"Server": "Mpilgrim", "Database": "Master", "UID": "sa",  "pwd": "Secret"}>>> params. Keys ()   (1) [' Server ', ' uid ', ' database ', ' pwd ']>>> params. VALUES () (2) [' Mpilgrim ', ' sa ', ' master ', ' secret ']>>> params. Items (  3) [(' Server ', ' Mpilgrim '), (' uid ', ' sa '), (' Database ', ' Master '), (' pwd ', ' secret ') ]

(1) The Keys Method of dictionary Returns a list that contains all the keys. The list is not output in the order defined by dictionary (because the elements in dictionary are unordered).

(2) The values method returns a list that contains all the values. It is the same order as the list output returned by the keys.

(3) The Items function returns a list of a tuple of the form (Key,value), which includes all the data in the dictionary.

11. Connecting list with split string

Connect list

Return ";". Join (["%s=%s"% (k, V) F or K, V I nparams. Items ()])

String ";" is itself an object, and the call to join method is to concatenate the elements in the list into a single string, each separated by a semicolon. The delimiter does not have to be a semicolon, it does not even have to be a single character, it can be any string.

Join can only be used for a list of elements that are strings, and it does not make any coercion of type conversions. Connecting a list that exists with one or more non-string elements throws an exception.

Split string

>>> li = [' se rver=mpilgrim ', ' uid=sa ', ' database=master ', ' pwd=secret ']>>> s = ";". Join (LI) >>> s ' Server=mpilgrim;uid=sa;database=master;pwd=secret ' >>> s.split (";")     (1) [' Server=mpilgrim ', ' uid=sa ', ' Datab ase=master ', ' Pwd=secret ']>>> s.split (";", 1)  (2) [' Server=mpilgrim ', ' Uid=sa;datab Ase=master;pwd=secret ']

(1) In contrast to join, split splits a string into a multi-element list. Where the delimiter is completely removed.

(2) Split accepts an optional second parameter, which is the number of times to split.

"Dive into Python" Chapter 2 and Chapter 3 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.