21-Day Learn Python notes (i)

Source: Internet
Author: User

One

If Chinese is included:

1, or in the file header add: # CODING=GBK

2, the file is changed to UTF-8 no BOM format encoding

Two

Python Case-sensitive

Python can be nested in single and double quotes without escaping

Python program requirements are best used in all indented hierarchies

The ":" At the end of the line represents the beginning of the next line of code indentation, and if only one statement is indented, it can be written directly after the ":"

Code at the same level as much as possible to keep it consistent

The Python programming specification states that indentation is best in the form of spaces, where each layer is best to indent 4 spaces to the right

Single-line comments with #

Block annotations surround the program with three single quotes or three double quotes

Python can also write two statements in the same line, separated by semicolons.

If a line can not be written like C ' \ ', if in parentheses, for example, many parameters \ can also be removed, and C as

Multiplication Sign In Python formulas cannot be omitted.

To compare whether two floating-point numbers are equal, you should see if their difference is less than a very small number.

Three

The string can be taken out of one of the characters by ordinal, such as: ' ABCDE ' [1] Gets the value of B.

Python strings can be operated with "+", "*".

The split function of string returns a string separated into a list with the specified character, but does not change the original string.

The string's join function inserts the original string between every two characters in the argument string, and returns the argument string if the argument string has only one character. The same join does not change the original string, just returns a new string.

The/Operator results in floating-point numbers, even if two integers are divided.

is the divisible operator

The original string is either R or R as a flag before the string, and this notation is commonly used to represent delimiters in the path as R ' C:\Windows\System ' in the Windows system, and the original string must not end with "\"

Python string formatting: print ("I am a%s.",% "Programer")

The default in Python is the Utf-8 encoded string, which is required to be converted to a byte string (bytes) when sending a string on the network, then it is the string's encode () method, which returns a byte string (bytes) in the form of the following:

Encode (encoding= ' utf-8 ', errors= ' strict '), encoding default encoding is Utf-8, can also be encoded using GBK, gb2312, encoding and decoding specified encoding type should be the same, This will restore the string correctly.

In Python, the "=" function is to bind an object reference to an object in memory, and if the object already exists, it is simply bound to refer to the right object, and the "=" operator creates the object and binds it if the object does not exist.

At any one time, an object reference can re-reference a different (type) object

Python performs type checking at run time and throws an error once it is not operational

The list supports addition operations, multiplication operations

Tuples can be seen as a special list, unlike lists where tuples cannot be changed once they are established, or they can be referenced by ordinal numbers.

The member is accessed through a key in the dictionary and cannot be accessed by its location.

The logical false in Python includes: none, False, 0, ' (empty string), (), [], {} Any other value is considered true

The logical operators in Python include: and, or, not

The result of not can only be true or false

Or is the OR operator, returns the first operand directly if the first operand is true, or returns the value of the second operand or expression if False

and is the AND operator, returns the first operand directly if the first operand is false, or returns the value of the second operand or expression if true

Is and is are not both two-tuple operators that determine whether the left and right object references point to the same object

In and not in are called member operators to check if a data exists in a data type that contains multiple members, and the member operator checks for a key member instead of a value member for the dictionary

The sequence represents a collection of ordered objects that are indexed as nonnegative integers, including the string, list, and pairs tuples groups described earlier. Strings are sequences of characters, and lists and tuples are sequences of arbitrary python data types or objects. Strings are also immutable, modifying a string is a re-creation of a string

A slice of a sequence refers to a part of a member data item in a sequence, such as [Start:end:step], that takes a series of members from the start ordinal to the end of the end, takes a member every step, and the element taken by the slice starts from start and ends with an end. Does not include an element with an end ordinal

SUM (S[,start]) returns the sum of the items in S

All items in all (s) s are true, then return true, otherwise false

If an item in any (s) s is true, it returns true, otherwise false

Four

If statements are not bracketed, end with: End, else statements are followed by: End Elif Similarly, nesting is nothing special. Use as little nesting as possible, hard to read.

The IF statement can be used in a single statement to implement the ternary operator, the basic form is as follows:

< expression 1> If < condition > Else < expression 2> Its semantics is to get the value of expression 1 when the condition is true, otherwise get the value of expression 2

A = None

b = 3

x = b If A is not none of else 0 when the value of a is not none, the X value is 3, otherwise x is taken as 0

The For statement is not enclosed in parentheses, ending with:.

For i in [1,2,3,4,5]:

Print (I, "squared is:", i*i)

Else

Print (' Loop end! ')

You can use continue and break in a for statement, followed by a colon, similar to the use of C

ADCT = {' Apple ': +, ' banana ': $, ' pear ': 35}

For Key,value in Adct.items ():

Print (Key, ': ', value)

For key in Adct.keys ():

Print (key)

For value in Adct.values ():

Print (value)

The range function used by the For loop has three parameters, the first one is the initial value, the second is the maximum value does not contain the value, and the third is the value of each sliding scale.

The enumerate function is used to traverse the subscripts of elements in a sequence and they :

a=[1,2,3]

For I, D in enumerate (a):

Print (I,":",D)

0:1

1:2

2:3

The ZIP function accepts any number of sequences (including 0 and 1) as parameters, returning a tuple list.

b = (2,4,6)

For i,j in Zip (A, B):

Print (I, ":", J)

1:2

2:4

3:6

Because the dictionary has both a key and a value, you cannot traverse the dictionary directly during traversal 20 through the dictionary's items (), keys (), values () and other methods to traverse their keys and values, keys, values. If you traverse both the key and the value, you can use two loop variables to receive the keys and values separately during traversal.

The range () function does not generate the entire sequence at the time of invocation, but rather traverses it once to produce a value that reduces memory footprint, which is essentially an iterator.

A while loop does not look like a for loop can traverse a collection of objects

The while loop does not have parentheses, end with: ends, or it can use else to determine what to do when the loop ends.

Alst = [1,2,3,4,5]

Total = Len (alst)

i = 0

While I < total:

Print (I, "squared is:", I * i)

i = i + I

Else

Print (' End of loop! ‘)

The result prints a square of 0 to 4.

Derivation, a way of generating a new sequence using the original sequence

>>>a = [1,2,3,4]

>>>[2*i for I in a]

[2, 4, 6, 8]

>>>b = [' A ', ' B ', ' C ']

>>>{k:v for k,v in zip (b, a)}

{' B ': 2, ' C ': 3, ' a ': 1}

>>>[2*i for I in a if I% 3! = 0]

[2, 4, 8]

>>> a = [1,2,3,4]

>>> [5+i for i in a if I% 3! = 0]

[6, 7, 9]

Python has several common iterative functions built into it, which are both convenient and practical.

Enumerate (SEQ) Number Iteration

Sorted (seq) Sort Iteration

Reversed (seq) Reverse Iteration

Zip (seq1,seq2,...) Parallel iterations

The numbering iteration returns both the element in the sequence and the number of the element in the sequence (numbering starts at 0), and when the for statement is numbered, the number and the value of the element should be received using two loop variables respectively.

The purpose of a sort iteration is to iterate through the smaller values in the sequence, and then traverse the larger values in the sequence, which, of course, require that the data in the sequence be the same sort of data. You only need one variable to

The inverse iteration is the traversal of the elements in the iteration sequence from the tail to the head

Parallel iterations are also a very useful iterative function, which is the same ordinal element in the sequence of seq1, SEQ2, and so on, which is simultaneously traversing the function.

When the length of a sequence value in a parallel iteration function is inconsistent, only the length of the shortest sequence is traversed

The basic form of a typical list derivation is as follows:

[<i-related Expressions > For i in Aiterator]

Aiterator refers to an object that can be traversed, such as a list, a tuple, or a range () function. Its semantics is to use the loop variable i to traverse aiterator, and put the value of the I-related expression into a list.

A dictionary can also implement its derivation syntax, which has the following basic format:

{key_exp:value_exp for key_exp, value_exp in Aiterator}

The list derivation and dictionary derivation can not only handle all the traversed elements, but also use the IF statement to implement the elements of the selected processing traversal sequence in the following basic form:

[<i Related Expressions > For i in Aiterator if < condition;]

{key_exp:value_exp for key_exp, value_exp in aiterator if< condition;}

If you want to get a list of all the squares in a 1~10, and the square value is an even number, you can do so using the following code:

Square_odd = [I**i for i in range (1, one) if i**i%2 = = 1]

If you apply a function in an evaluation expression or conditional expression in a derivation, you can construct a more complex derivation to implement batch processing of the data in the sequence (which is also often referred to as declarative programming).


This article is from the "Clear" blog, please be sure to keep this source http://ggxxjj123.blog.51cto.com/1079641/1768088

21-Day Learn Python notes (i)

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.