Python Learning notes (7-11)

Source: Internet
Author: User
Tags assert case statement switch case

Seven, the dictionary

A python dictionary is a variable-length hash table.
Has_key whether the query has this key value.
Add as long as you assign a value to a new key.
Delete one with Del, delete all with clear
changing or adding new elements can be used with the update
Get returns the key value through the key value, if there is no key, then return null (python with none means null)
Get also has a second parameter that sets the return value when there is no key. However, if you use the SetDefault setting, the second parameter of get is invalid.
Items use the list to load the structure of the table column tuple to return content.
Keys returns the key value as a list
Values returns a key value as a list

A key can only correspond to one value

Traverse Dict can be used for I in Dict1:print I,dict1[i]

---------------------------------------------------

Eight, the statement

Nothing special, that is, while,for more an else, for the normal cycle to use after the break out of the No.
There is no switch case statement.
For a variable in list

Range (Start=0,end)
Range (Start,end,slep=1)
A list from start to End-1 (or from 0 to end-1) is produced, and Slep represents the interval between values and values.
Xrange () is intended for use in a For loop, and is suitable for building larger lists.

There's no difference between break and continue and C language.
Pass and VC null, when you do not know what to do with the short statement.
are not bracketed.

---------------------------------------------------

IX. Documents

Open (file name, open mode, buffer)
Open mode has r,w,a,+, where B is useless, because Linux is a binary file type.
The buffer is from 0 to a value, and if 1 uses the system default.
Read reads the set number of bytes, which defaults to-1, to the end of the file.
ReadLine reads the current line. The file pointer jumps to the next line.
ReadLines reads the list by line.
Flush writes the buffered content to the file.

Write writes a file
Writelines write the list as a file, note that the default does not add line breaks, you need to add it yourself. Such as:
>>>output=[' 1 ', ' 2 ', ' 3 ']
>>>[x+ ' \ n ' for x in output]
[' 1\012 ', ' 2\012 ', ' 3\012 ']

Seek to change the file pointer.
0 Seek_set File Header
1 Seek_cur Current Position
2 seek_end file Tail

Tell to get the current file location
Close File
Next is the same as ReadLine, but after the end of the file it will go wrong and ReadLine will read empty.
Truncate truncating files

The sign of the end of the file is the read-out data = = "", note that the empty behavior ' \ n ' is not empty, only to the end is empty.

The file also has several parameters that can be used, note that without parentheses, is the property is not a method.
closed//is not already closed
mode//Last Open mode
name//full path and file name

Raw_input (' Enter: ')
Equivalent
Sys,stdout.write (' Enter: ')
Sys.stdin.readline ()

SYS.ARGV is a list of command-line arguments.
Without argc, you can use Len to get it. Argv[0] is the full path and file name of the file.

The OS module provides operations on the file. Check the Help file for more details. P199

The 2 modules of pickle and shelve can be stored directly in the file by dump (), load (), and then read it the next time. Test a bit very useful, although the C program can be the structure or the class to write to the file, but this unexpectedly can also directly put the definition of the class to write in.

The Fileinput module iterates through all the data rows of multiple input files.
The Getopt module provides analysis and processing of command-line parameters.
The Glob and Fnmatch modules provide a UNIX-style wildcard matching feature.
The gzip and zlib modules and ZipFile allow for automatic compression and decompression when accessing files.
The Shutil module provides advanced file access, copy file access, recursive replication directory tree, and more.
The C and Stringio modules implement the file-style operation interface at the top of the string object.
The Tempfile module generates temporary file names or temporary files.

---------------------------------------------------

Ten, abnormal



Try-except......except-else and try-finally cannot be generalized.
Try-finally, whether or not it is an exception, will execute.

Except can add multiple exceptions, such as: Except (Aerror,berror):
Except can also take a parameter, which is the exception when given some information, may be many types, need to judge, such as: Except (aerror,berror), argument: When used, can be obtained by str (argument).

Try:except:else: If you use except: Captures all exceptions, then else executes when no exception occurs.

Raise can throw an exception on its own
Raise[exception[,args[,traceback]]
Exception can be a string of a class or an instance.
Args represents an optional parameter that prompts the user to see.
Traceback helps the user to re-throw an identical exception, which is not normally used.
Raise ' 111 ' then the exception content is ' 111 ', can be used except ' 111 ': Capture.

An assert throws an exception if the condition is met
Assert Expression[,arguments]
Like what:
Try
Assert 1==0, ' 1!=0 '
Except Assertionerror,args:
print '%s:%s '% (Args.__class__.__name__,args)
Execution results
Assertionerror:1!=0

Sys.exc_info () can get exception content.

---------------------------------------------------

Xi. functions

Variable length parameter: The formal parameter is preceded by a * to indicate the variable number of parameters.
For example: Def foo2 (arg1,arg2,*therest):
When using them in a function, the variable number of arguments later is used as a list, for I in Therest:.
When calling a function, you can Foo2 (1,2,11,12,13,14) and the next 4 parameters are placed in the list therest.
If you use * *, you can pass it as a dictionary, such as: Def Foo3 (arg1,arg2,**therest):
When using them in a function, use for I in Therest.key () as a dictionary:
When calling a function, you can Foo3 (1,2,c= ' Grail ', d=123)
Note that the position of C and D can only be placed in a string, and cannot be quoted, otherwise the error is indicated.
You can actually pass * () and **{} as arguments.

The function does not support polymorphism, and a function with the same name as defined later makes the previously defined invalid.

Lambda creates anonymous functions.
Lambda [arg1,arg2]: expression
Def foo1 (): return 1 equals lambda:1
Foo2=lambda:1, for example, Foo2 and foo1 function the same.
such as the summation function, is the lambda x,y:x+y

Apply
Foo (3, ' abc ') equals Apply (foo, (3, ' abc '))
Similar functions also have filter map reduce

Functions that run outside the function can still be used in custom functions, because Python does not have a main function, so the functions defined in the execution statement are global functions.
A1=1
def foo ():p rint A1 result is 1.
Note that if you define a variable first, you cannot modify the global variable in the post-write custom function, such as this A1
If the variable is defined later, then in the custom function of the preceding write, this is the value of 2, think that the general need to use global to declare.
But note that in class, the variables defined here are useless and need to be declared with global.


This article is from "Flying Justice Blog" blog, please be sure to keep this source http://xzq2000.blog.51cto.com/2487359/1766837

Python Learning notes (7-11)

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.