Chapter 2 and Chapter 3 in Dive into Python, divew.python

Source: Internet
Author: User

Chapter 2 and Chapter 3 in Dive into Python, divew.python

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", \    "database":"master", \    "uid":"sa", \    "pwd":"secret"    }    print buildConnectionString(myParams)

Output result of odbchelper. py:

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

1. function declaration

Functions in Python do not need to specify the Data Type of the returned value, or even whether the returned value exists. In fact, each Python function returns a value: If the function executes the return statement, it returns the specified value; otherwise, it returns None (a null value in Python ).

2. docized Functions

You can document a Python function by providing a doc string.

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

Double quotation marks indicate a multi-line string. Everything between start and end quotation marks is considered part of a single string, including hard carriage return and other quotation marks. Everything in double quotes is the doc string of this function, which is used to describe what the function can do. If doc string exists, it must be the first content to be defined by a function (that is, the first content after the colon ).

3. All objects

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

4. Test Module

All Python modules are objects and have a built-in attribute _ name __. The value of _ name _ of a module depends on how you apply the module:

If the import module is used, the value of _ name _ is usually the module file name, 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 within the module:

if __name__=="__main__":

When the module is run directly, the value of __name _ is _ main __, so the test suite is executed. When the module is imported, the value of __name _ is something else, so the test suite is ignored. This makes it much easier to develop and debug new modules before they are integrated into a large program.

5. 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 with two elements assigned to variable d. Each element is a key-value pair. The entire element set is enclosed in braces.

(2) 'server' is a key, and its associated value is referenced by d ["server"], which is 'mpilgrim '.

(3) The value can be referenced by the key, but the key cannot be obtained by the value.

(4) Duplicate keys cannot exist in a dictionary. Assigning a value to an existing key will overwrite the original value.

(5) 1. You can add a new key-value pair at any time. 2. dictionary is unordered.

The key of a dictionary is case sensitive (that is, case sensitive ).

Dictionary is not only used to store strings. Its values 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. You can mix and match values as needed. The keys of a dictionary must be strict.

Del dictionary [key] uses the key to delete independent elements from a dictionary.

Dictionary. clear () clears all elements in dictionary.

6. List)

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

Append accepts a parameter (which can be any data type) and simply appends it to the end of the list. Extend accepts a parameter, which is always a list and adds each element in the list to the original list.

Insert inserts a single element into the list. The value parameter is the index of the insert point.

Index searches for the first appearance of a value in the list and returns the index value. If no value is found in the list, python will throw an exception.

To test whether a value is in the list, use in. If the value exists, True is returned; otherwise, False is returned. The first letter of True and False must be capitalized.

Remove removes the first appearance of a value from the list. If this value is not found, python returns an exception.

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

List can be connected using the + operator. List = list + otherlist is equivalent to list. Extend (otherlist ).

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

* The operator can act as a repeat on the list. Li = li * 3 connects the three lists into one.

7. Tuple)

Tuple is an unchangeable list. Once a tuple is created, it cannot be changed in any way.

Tuple is defined in the same way as list, but the entire element set is surrounded by parentheses rather than square brackets.

The tuple elements are sorted in the same order as the list elements.

Tuple has no method, but you can use in to check whether an element exists in tuple.

Benefits of using tuple:

  • Tuple is faster than list operations. If you define a constant set of values and use it to traverse it continuously, tuple should be used instead of list.
  • If you perform write protection on data that does not need to be modified, the code can be safer.
  • Tuple can be used as a key in dictionary, but the list cannot. The Dictionary key must be unchangeable.
  • Tuple can be used in string formatting.

8. Variable Declaration

When a command is divided into multiple rows by the "\", subsequent lines can be indented in any way.

Assign multiple values at a time

>>> v = ('a','b','e')>>> (x,y,z) = V>>> x'a'>>>y'b>>>z'e'

V is a three-element tuple, and (x, y, z) is a three-variable tuple. Assign a tuple value to another tuple and assign 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 with an integer element.

9. format the string

String formatting

>>> uid = "sa">>> pwd = "se cret">>> print pwd + " isnot agood passwor d for " + uid       (1)secret is not agoodpasswo rd for sa>>> print "%s is nota good passw ord for %s" % (pw d,uid) (2)secretis not agood passwo rd for sa>>> userCou nt = 6>>> print "Users con nected: %d" %(use rCoun t, )         (3) (4)Users connected:6>>> print "Users con nected: " + userCoun t               (5)Traceback (innermost last) :File "<i nteract ive input>", line 1, in ?TypeError: cannot concatenate 'str'and 'int' objects

(1) connect through the join operator "+"

(2) Achieve connection through string formatting

(3) (userCount,) is a tuple that contains only one element. When defining a list, tuple, or dictionary, it is always followed by a comma after the last element. However, when defining a tuple that only contains one element, a comma is required. If Commas are omitted, python does not know whether (userCount) is a tuple containing only one element or the value of the variable userCount.

(4) to format the string, replace % s with % d to process the integer.

(5) attempting to connect a string to a non-string will cause an exception. String connection only works when every connected string is a string.

Formatting numeric values

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

(1) The % f format character option corresponds to a decimal floating point number. If no precision is specified, a 6-digit decimal number is printed.

(2) Use the % f formatting option that contains the ". 2" precision modifier to print only two decimal places.

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

10. ing list

By applying a function to each element in the list, a list is mapped to another list.

>>> li = [1, 9,8, 4]>>> [elem*2 for elem in li]        (1)[2, 18, 16, 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 to be mapped. Python cyclically traverses every element in li. Perform the following operations on each element: First temporarily assign the value to the variable elem, then use the Python application function elem * 2 for calculation, and finally append 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 resolution result of a list to the variables mapped to it.

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 containing all keys. This list is not output in the order defined by dictionary (because the elements in dictionary are unordered ).

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

(3) The items function returns a list of tuple, which is composed of keys and values. This list includes all data in the dictionary.

11. Connect list and split string

Connection list

return ";".join(["%s=%s" % (k, v) f or k, v i nparams. items()])

String ";" is an object, and the join method is called to connect the elements in the list to a single string. Each element is separated by a semicolon. The separator 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 the list where elements are strings. It does not perform any forced type conversion. An exception is thrown when a list with one or more non-string elements is connected.

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 multiple element lists. The separator is completely removed.

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

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.