Some of the notes that Python learns

Source: Internet
Author: User
Tags case statement

Python Learning: It's finally started.

date:2014.10.30

Python Chapter Eighth

    1. If expression:

Expr_true_suite

Consists of three parts, the keyword + expression + expression is true or non-zero code block, note to have a colon, the following statement needs to be indented.

    1. A single if statement can be either a Boolean operator and, or, a multiple conditional judgment or a negative judgment.
    2. In If, 0 and none, "" and so on are all false types.
    3. If the code for a compound statement (such as an IF clause, while, or for loop) contains only one line of code, it can be written on a single line with the preceding statement, but it is recommended to indent according to the specification.

Example: Both are legal statements

if (4>2) or (2==1):p rint 222

For I in range:p rint I

while (4>2):p rint ("OK"*10) "OK" *10, print 10 times

    1. If expression:

Expr_true_suite

Else

Expr_false_suite

    1. A fun example, almost crazy:

A = Raw_input ("input a number")

a = Int (a)

If a > 0:

Print a

if (a <= 100):

Print "a>=0 and a<100"

Else

Print a>100

Else

Print "Your put is <0"

The result of the input output is a string instead of a numeric value, so it must be converted, or the string and number comparisons will occur.

    1. An if statement can have at most one else, but can be used by any of the elif to replace the switch/case statement.

Example:

if User.cmd = = "Create":

ACTION = "Create Item"

elif Users.cmd = = "Insert"

Action = "Insert Item"

elif Users.cmd = = "Delect"

Action = "Delect item"

Else

Action = "Try again!"

    1. Workaround, use in and not in; Use sequence and member relationship operators to simplify:

A = Raw_input ("input:")

If a in ("Create,insert,delect"):

Action = "%s Item" % A

Else

Action = "Try again!"

Print action

    1. Dictionary alternatives, dictionaries are searched directly by key, and are much faster: more elegant

A = Raw_input ("input:")

Mydict = {"create":"Create item",

"Insert":"Insert Item",

"delect":"delect item"}

default = "Try again!"

Action = Mydict.get (A,default)

Print action

    1. Ternary operator: X if C else Y
    2. While expression:

Suite_to_repeat

Such a loop mechanism is often used in the counting cycle, which is to set a variable, in the Loop statement +1, in the while to judge.

Count = 0

While Count <9:

Print "index is:" , Count

Count+=1

    1. The infinite loop of the while is used for server and client programming.
    2. A powerful looping mechanism for loops that can traverse the sequence members, used in list parsing and generator expressions.

For Iter_var in iterable:

Suite_to_repeat

The For loop accesses all elements in an iterative object and ends the loop after all entries have been processed, which can be used for any iteration, especially database operations, and can be obtained by an iterator or by a count operation.

    1. For the sequence type:

String type:

For Eachletter in "Names":

Print "Current eachletter:", Eachletter

Loops each letter in a string. The letter is the element of the string. This usage is not common, but can be used as debugging, if it comes out of a single character proof sequence inside may be a string.

    1. Three basic methods of iterative sequences:

(1) Iterate through the sequence item:

For each in ["niu","qi","ke"]:

Print "%s,hi" % each note: There is no comma after the formatted output.

(2) iterating through the index of a sequence: the direct iteration sequence is faster than the iteration through the index

For index in range (len (names)):

Print "hi,%s" % Names[index]

(3) Using Item and Index iterations: using the Enumerate () function

For Index,name in Enumerate (names):

Print "%d:%s,hi" % (index+1, name) # put the following input values into a tuple.

16. For the iterator type:

The range () built-in functions are available in two ways: Range (start,end,step=1), start value, end value, and step size, which defaults to 1. This returns a list of all k, where K:start<=k and k<end, and increments by the value of each step, step cannot be 0, note that the end value is not included, which makes it more reasonable to use as an iterator, Because the subscript of the sequence is usually starting from 0 to length-1.

Another is the abbreviated syntax for range: The default start is 0, or the step size is 0.

Range (end), Range (Start,end) only in these forms.

The xrange () function is more appropriate when using xrange () in a large list of scopes. In fact, the range () function returns a list that consumes memory, and xrange () generates an xrange () object that does not return a list.

18. Built-in functions related to sequences:

Sorted (), sort

The zip () function, for name,age in Zip (names,ages), connects two sequences together.

The break statement is the end of the current loop. Continue will ignore the following loop statement and return to the top, but still need to make a judgment, only after the validation of the success of the new cycle

20. Using iterators, you can create an iterator:

Mytuple = (123, "Vde", "Eee")

I = iter (mytuple)

Next ()

For I in seq:

Do_something_to (i)

Actually:

iter = iter (seq)

While true:

Try

I = Iter.next ()

Except:stopiteration:

Break

Do_something_to (i)

21. Iteration of the Dictionary: Dict.iterkeys (), Dict.itervalues (), Dict.iteritems ()

Eachline in myfile accesses each row in the myfile. Of course, open ("filename") first.

23. Variable sequences can be modified when iterating over mutable objects: But most of them are immutable except for lists, so use them with caution.

A = ["h123","h234","sss"]

For I in A:

If not I.startswith ("H"):

A.remove (i)

Print a

24. List analytic type;

[Expr for Iter_var in iterable]

Iter_var does not necessarily appear in an expression.

[X**2 for X in range (6)]

Extended: [Expr for Iter_var in iterable if COND_EXPR]

25. Iteration Matrix: Two for is useful, the list parsing is very powerful

[((X+1), (y+1)) for X in range (3) for Y in range (5)]

Generator expression: (expr for Iter_var in iterable if cond_expr) can see that this generated is also an iterator object.

data:2014.10.31

Python Learning: The Nineth Chapter

    1. The open () function, with particular attention to the forward slash here, is shown in the following example

File_object = open (File_name,access_mode = ' r ', buffering =-1)

The mode in this refers to the open pattern, and R is the only read; W is write and A are appended; U means universal line break support. Where a file opened with R or U must exist, the file opened with ' W ' will be emptied and then recreated. The ' a ' pattern exists for append data, even if you seek, the file will be appended to the end, and if the file does not exist, it will be created automatically. The file name extension to be indicated. In addition there are "w+", "r+" and other forms.

The r+ form is in the back append; R can only be read, W can only be written, and the previous data is overwritten, a can only be appended.

R+ can read and write, w+ read without exception, but can not read the data, writing will overwrite the previous data. A + reads without exception, but cannot read the data and append it later.

Try

File = open ("C:/unintall.log")

Except IOError:

Print "I do not find the file"

For eachline in file:

Print Eachline

    1. The factory function file () is the same as the open () function, using open () for reading and writing, and then using file () when explaining the processing of the file object. Open () is more like a method, and file () is more like a created function, because they are returned with the same object, so they can be replaced, but still be differentiated.
    2. File methods can be divided into 4 categories: input, output, intra-file move, and miscellaneous operations.
    3. Input: The Read () method, which reads bytes directly into a string, reads up to a given number of bytes, and if no size or negative number is given, the file is read to the end. The future is likely to be deleted.
    4. ReadLine (): Method reads a single line of open files (reads all bytes before the next line terminator), and then the entire line, including the line Terminator , is returned as a string. In the same way as read (), the default size is-1, and if a byte is set that is not sufficient to return a full row, then some of the row content is returned.
    5. The ReadLines () method reads all remaining row data, returns a list of strings, or sets the size of Sizehint, which represents the maximum number of bytes returned. There is also a xreadlines method that, like the xrange () above, does not directly create a list, thereby reducing the use of memory. However, because of the introduction of iterators and file iterations, ITER (file) can be used instead, and it is not necessary to use Xreadlines ().
    6. The Writelines () method is a list-based operation that takes a list of strings as a parameter

and write them to the file. The line terminator is not automatically added, so if necessary, you must add a line terminator to the end of each line before calling Writelines ().

    1. Look at an example:

Try

File = open ("c:/users/niuqk/desktop/test1. TXT"," R ")

Except IOError:

Print "I do not find the file"

# for Eachline in File.readlines ():

# Print eachline

data = [Line.strip ("\ n") for line in File.readlines ()]

Print data

In this case, there is no comment before the desired effect, because file.readlines () read all the data at once, there is no data to read, the result is empty. S

    1. OS file system, and Os.path operation:
    2. data = [line for lines in file] printed a newline character

[' Niuqike is Ok!niuqike are Ok!niuqike is ok!\n ', ' niuqike is ok!\n ', ' niuqike was ok!\n ', ' niuqike is ok! ']

data = [Line.strip ("\ n") for line in file]

data = [File.readline ()]

Print data

Note: This is a printed letter, including line breaks

data = [File.readlines ()]

Print data

If you want to remove line breaks using the strip ("\ n") method

    1. 11.   file after use should remember to close, this and the database is the same, in fact, all the connection resources are best used after the release, this should be noted, is a good programming habits.
    2. 12.   Although when the number of references to a file object changes to 0 , when the unique variable name is assigned again, The garbage collection mechanism of Python automatically closes the file, but good programming habits should still be explicitly given off before the assignment is re-given.
    3. 13.   file.truncate Understanding: This is actually intercepting size The contents of the are left in the text, meaning that the text after the size is deleted.
    4. 14.   os Learn: OS.GETCWD () Get the current work directory to the package name hierarchy.
    5. 15.   Note that the escape character \ use, everything to \ Place to consider whether or not to escape, there is a path in the c:\users\niuqk\desktop\kong  in which the \ n is exactly a line break, A lot of errors occur. C:\Users\niuqk\Desktop\kong
    6. 16.    python do not escape strings using R

MyFile = open (' C:\new\text.dat ', ' W ')

This will be mistaken for a newline character, \ t as a tab, and escaped,

Therefore, you can add an R, indicate the raw character, and do not escape

MyFile = open (R ' C:\new\text.dat ', ' W ')

Some of the notes that Python learns

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.