Python basic learning notes 2, python basic learning notes

Source: Internet
Author: User
Tags unpack

Python basic learning notes 2, python basic learning notes
Dictionary

A dictionary is similar to a list and can store multiple elements. Objects storing multiple elements are called containers );

Common ways to create a dictionary:

>>>dic = {'tom':11, 'sam':57,'lily':100}>>>print type(dic)

Similar to a table, each element is separated by a comma. Each element contains two parts, key and value. (objects that cannot be changed can be used as keys ). Values can be any object; keys and values correspond to each other;

Different from a table, the dictionary elements have no order. You cannot reference an element by subscript. A dictionary is referenced by a key.
>>>print dic['tom']>>>dic['tom'] = 30>>>print dic

 

Add a new element to the dictionary:

>>>dic['limi'] = 99>>>print dic
Here, we reference a new key and assign it the corresponding value. Cyclic call of dictionary elements
dic = {'lilei': 90, 'lily': 100, 'sam': 57, 'tom': 90}for key in dic:    print dic[key]

In a loop, each key of dict is extracted and assigned to the key variable.

With the print result, we can confirm again that the elements in dic are unordered.   Common dictionary Methods
>>> Print dic. keys () # Return All dic keys> print dic. values () # Return All dic values >>> print dic. items () # Return All dic elements (key-value pairs)> dic. clear () # clear dic And change dict {}

 

There is also a common usage:
>>> Del dic ['Tom '] # Delete the 'Tom' element of dic.
Del is a reserved keyword in Python and is used to delete objects. Similar to a table, you can use len () to query the total number of elements in the dictionary.
>>>print(len(dic))

 

Text File Input and Output   Create a file object

Open a file and use an object to represent the file:

F = open (file name, mode:

"R" # Read-Only

"W" # write for Example
>>>f = open("test.txt","r")

The specific usage needs to be put into practice. Here is a brief summary.

  Module In Python, A. py file forms a module. Through the module, you can call programs in other files. Introduction moduleWrite a first. py file with the following content:
def laugh():    print 'HaHaHaHa'

 

Write another second. py and introduce the program in first:
import firstfor i in range(10):    first.laugh()
In second. py, we use the laugh () function defined in first. py.

After a module is introduced, an object in the introduced module can be called through the module. Object method.

In the above example, the first is the introduced module, and laugh () is the object we introduce.

 

There are other import methods in Python,

Import a as B # introduce module a, and rename module a as bfrom a import function1 # introduce the function1 object from module. When calling an object in a, we do not need to describe the module, that is, directly use function1 instead of a. function1. From a import * # introduce all objects from module. When calling an object in a, we do not need to describe the module, that is, directly use an object instead of a. object.

These Reference Methods facilitate subsequent program writing.

  Search module path

Python will search for the module it is looking for in the following path:

If you have a custom module or a downloaded module, you can put it in the corresponding path as needed so that Python can find it. Module package

You can place modules with similar functions in the same folder (such as this_dir) to form a module package. Pass

import this_dir.module
Introduce the module in the this_dir folder. This folder must contain a _ init _. py file to remind Python that the folder is a module package. _ Init _. py can be an empty file.   Function Parameters   Value Transfer
def f(a,b,c):    return a+b+cprint(f(1,2,3))
When f is called, 1, 2, 3 are passed to a, B, and c respectively based on their locations.   Keyword Transfer

In some cases, it may feel rigid to use location transfer. Key word transmission is based on the name of each parameter.

Keyword does not follow the corresponding relationship of location. The above f definition is still used to change the call method:

print(f(c=3,b=2,a=1)) 

Keyword transfer can be mixed with location transfer. However, the location parameter must appear before the keyword parameter:

print(f(1,c=3,b=2))

 

Default Value

When defining a function, you can assign the default value to the parameter in the form of c = 10 ).

If this parameter is not passed, the default value is used.

def f(a,b,c=10):    return a+b+cprint(f(3,2))print(f(3,2,1))

When function f is called for the first time, we do not have enough values. c is not assigned a value, and c uses the default value 10.

When the second function is called, c is assigned a value of 1 and the default value is no longer used. Package TransferLocation transfer, in fact, is a tuple

The following is an example of parcel location transfer:

def func(*name):    print type(name)    print namefunc(1,4,6)func(5,6,7,1,2,3)

Two calls, although the number of parameters is different, are defined based on the same func. In the func parameter table, all parameters are collected by name and merged into a tuple according to the position. This is the transfer of the package location.

To remind the Python parameter, name is the name of the tuples used for package location transfer. When defining func, add the * sign before name. The following is an example of transfer of wrap keywords: dictionary Transfer
def func(**dict):    print type(dict)    print dictfunc(a=1,b=9)func(m=2,n=1,c=11)

Similar to the preceding example, dict is a dictionary that collects all the keywords and passes them to the function func.

. To remind Python, The dict parameter is the dictionary used for the transfer of the wrap keyword, and ** is added before dict **.

The key to package transfer is to add * or ** before the corresponding tuples or dictionaries when defining functions **. Unpack

* And ** can also be used when calling, that is, unpacking. The following is an example:

def func(a,b,c):    print a,b,cargs = (1,3,4)func(*args)

In this example, the so-called solution package enables each element of the tuple to correspond to a location parameter when transferring the tuple.

Use * when calling func to remind Python:

I want to split args into three scattered elements and pass them to a, B, and c respectively. (Imagine that when calling func, what are the consequences of not * Before args ?)

Correspondingly, there is a solution package for the dictionary, using the same func definition, and then:

dict = {'a':1,'b':2,'c':3}func(**dict)

When passing the dictionary dict, each key-value pair of the dictionary is passed as a keyword to func.

  Cycle Design   Range ()

In Python, if the in after a for loop follows a sequence, the sequence elements used for each loop are not the subscript of the sequence.

We have used range () to control the for loop before. Now, we continue to develop the range Function to control the loop by Subscript:

S = 'abcdefghijk'for i in range(0,len(S),2):    print S[i]
In this example, we use len () and range () Functions and I as the subscript of the S sequence to control the loop. In the range function, the upper limit, lower limit, and step size of each loop are defined respectively. This is similar to the for loop in C. Enumerate ()

Using the enumerate () function, you can get the subscript and element in each loop at the same time:

S = 'abcdefghijk'

for (index,char) in enumerate(S): print index print char

In fact, in each cycle of enumerate (), a value table (tuple) containing two elements is returned.

  Zip ()

If you want to extract one element from multiple equi-length sequences in each cycle, you can use zip () to conveniently implement the following:

ta = [1,2,3]tb = [9,8,7]tc = ['a','b','c']for (a,b,c) in zip(ta,tb,tc):    print(a,b,c)

In each loop, an element is extracted from left to right from each sequence and merged into a tuple. Then, the tuple elements are assigned to a, B, and c.

The zip () function extracts one element from multiple lists in sequence. The elements extracted each time (from different lists) are combined into a single tuple, And the merged tuples are placed in the list returned by the zip. The zip () function is used to aggregate the list. Parse zip ():
>>> ta = [1,2,3]>>> tb = [4,5,6]>>> zipped = zip(ta,tb)>>> print type(zipped)<type 'list'>>>> print zipped[(1, 4), (2, 5), (3, 6)]>>> print zipped[1](2, 5)

 

Loop objectA circular object is such an object. It contains a next () method (_ next _ () method, in python 3x ), the purpose of this method is to proceed to the next result, and after the end of a series of results, the StopIteration error is cited. Example: assume we have a test.txt file: 1234
Abcdefg

Run the following python command line:

>>>f = open('test.txt')>>>f.next()>>>f.next()...

 

Input f. next () until the StopIterationopen () returns a loop object that contains the next () method. The next () method returns the content of a new row each time, and the StopIteration is cited at the end of the file. In this way, we perform a loop manually. Automatic:
for line in open('test.txt'):    print line

 

Here, the for structure automatically calls the next () method and assigns the return value of this method to line. The loop will end when StopIteration occurs. Compared with sequences, the benefit of using cyclic objects is that you do not need to generate the elements to be used before the loop starts. The elements used can be generated in a loop. In this way, space is saved, efficiency is improved, and programming is more flexible. Exception Handling Exception Handling is indispensable in project development. Exception Handling helps people debug and makes it easier for people to locate bugs Through richer information. Exception Handling can also improve program fault tolerance.

We mentioned a StopIteration exception when talking about circular objects. This exception is an error when the circular objects exhaust all elements.

Let's take it as an example to describe the Exception Handling of BenQ.

A program that contains exceptions: re = iter (range (5) for I in range (100): print re. next () print 'hahahahahaha'

 

First, we define a loop Object re, which will carry out five cycles, each time using an element of the sequence.

In the subsequent for loop, we manually call the next () function. When the loop reaches 6th times, re. next () does not return any more elements, but throws a (raise) StopIteration exception. The entire program will be interrupted. We can modify the above abnormal programs until they are perfect Without bugs. On the other hand, if we know the possible mistakes and possible types of mistakes when writing a program, we can define an emergency plan for this exception type.
re = iter(range(5))try:    for i in range(100):        print re.next()except StopIteration:    print 'here is end 'print 'HaHaHaHa'

 

In the try section, we add the error-prone part. We can keep up with limit t to explain what the program should do when the try clause StopIteration occurs. If no exception occurs, the Skip T section is skipped.

Then, the program continues to run, rather than being completely interrupted. The complete syntax structure is as follows:
try:    ...except exception1:    ...except exception2:    ...except:    ...else:    ...finally:    ...

 

If an exception occurs in a try, the execution exception will be assigned and the execution will fail. Exception layer-by-layer comparison, check whether it is prediction1, prediction2. .. until you find its ownership and execute the corresponding statement in limit T. If there is no parameter after limit T, all exceptions are handled by this program. For example:
try:    print(a*2)except TypeError:    print("TypeError")except:    print("Not Type Error & Error noted")

Because a is not defined, it is NameError. The exception is eventually caught by the progress T: part of the program.

If an exception cannot be handed over to an appropriate object, the exception will continue to be thrown to the upper layer until it is captured or the main program reports an error. For example, the following program
def test_func():    try:        m = 1/0    except NameError:        print("Catch NameError in the sub-function")try:    test_func()except ZeroDivisionError:    print("Catch error in the main program")

The try... limit t... structure of the subroutine cannot handle the corresponding error divided by 0, so the error is thrown to the upper-layer main program.

If there is no exception in try, the limit t part will be skipped and the else statement will be executed.

Finally is the last thing to do regardless of whether there are exceptions.

The process is as follows,

Try-> exception-> wait t-> finally

Try-> no exception-> else-> finally   Summary  
  • Dictionary
    • Dic = {'Tom ': 11, 'Sam': 57}
    • Add Element
      • Dic ['limi'] = 99
    • Note:
      • Key-value, which must be enclosed in quotation marks for key operations, whether defined or referenced.
      • The key value is unchangeable, and the value can be changed;
    • Dictionary element loop call
      • For key in dic:
    • Common Methods
      • >>> Dic. keys () # Return All dic keys
      • >>> Dic. values () # Return All dic values
      • >>> Dic. items () # Return All dic elements (key-value pairs)
      • >>> Dic. clear () # clear dic And change dict {}
      • >>> Del dic ['Tom '] # Delete the 'Tom' element of dic.
  • Text File Input and Output
    • Create a file object
      • F = open (file name, Mode)
        • Mode
          • "R" # Read-Only
          • "W" # Write
  • Module
    • Module reference
      • Import a as B
      • From a import function1
      • From a import *
    • Search module path
      • -Folder of the program
      • -Standard Library installation path
      • -Path included in the operating system environment variable PYTHONPATH
    • Module package
      • Put modules with similar functions in the same folder (such as this_dir) to form a module package
        • Import this_dir.module
        • Introduce the module in the this_dir folder
      • This_dir must contain the _ init _. py file, telling Python that this is a module package.
  • Function Parameters
    • Value Transfer
      • Location-based relationship
    • Keyword Transfer
      • Based on the keyword name
    • Default Value
      • You can use the default value instead of passing the value.
    • Package Transfer
      • Def func (* name ):
        • Func (, 6): Pass the numbers, 6 to the name as a tuple (, 6)
        • Func (5, 6, 7, 1, 2): Pass the numbers 5, 6, 7, 1, 2 to name as a tuple (5, 6, 7, 1, 2)
      • Def func (** dict ):
        • Func (a = 1, B = 9): Pass the number a = 1, B = 9 to dict as a dictionary ('A': 1, 'B': 9)
      • It is called package transfer for packaging and transmitting data together.
    • Unpack
      • Def func (a, B ):
        • Args = (1, 2)
          • Func (* args)
          • During the transfer, a tuple args is passed to three numbers.
        • Dict = {'A': 1, 'B': 2}
          • Func (** dict)
          • When passed, the dictionary dict is passed to three numbers.
        • Note that tuple is * And dict is **
  • Cycle Design
    • Range ()
      • Definition: upper limit, lower limit, step size
    • Enumerate ()
      • Returns the subscript and value.
    • Zip ()
      • Extracts one element from multiple lists in sequence.
    • For line in open('test.txt '):
  • Exception Handling
    • Try-> exception-> wait t-> finally
    • Try-> no exception-> else-> finally

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.