Python syntax elements

Source: Internet
Author: User
Tags control characters function definition pow random seed readline square root

0. Python is case sensitive

1. Input: Variable =input ("suggestive text")

2. Output: Print

3. The code hierarchy and frame are represented by indentation (four spaces), not after each statement;

4. Note: #表示单行注释, "three single quotes multiline comment" "," "" three double quotes multiline comment ""

5. Naming rules: A combination of uppercase and lowercase letters, numbers, and underscores, but the first letter can only be uppercase, lowercase, or underlined, and cannot use spaces. Non-alphabetic symbols such as Chinese can also be used as names

6. Synchronous Assignment Statement: Assign a value to multiple variables at the same time (the right n expressions are evaluated first, and then the expression results are assigned to the left) example X,y=y,x

7. Data type 6 types: Numeric type, String type, tuple type, list type, file type, dictionary type; function: Type (x), returns the type of x, applicable to all types of judgments

1. Three types of numbers:

1. Relationship:

Three types there is a gradual "extended" relationship: integer--, floating-point number, complex number

Mixed operations can be performed between different numeric types, resulting in the widest type after the operation

function: Int (), float (), complex ()

2. Integer type:

0x, 0X starts with 16 binary number
0b, 0B starts with 2 binary number
0o, 0O starts with 8 binary number

3. Floating-point number type:

There are limits to the numeric range of floating-point numbers in the Python language, as well as decimal precision. This restriction is related to different computer systems.

The scientific notation uses the letter "E" or "E" as the symbol of power, with a base of 10. The scientific notation means the following:<a>e<b> = A * ten b

4. Plural type:

In accordance with the plural concept in mathematics, z = a + BJ, A is the real part, B is the part of the imaginary number, A and B are floating-point types, the imaginary part is marked with J or J

For complex z, you can get the real part Z.imag by Z.real to obtain the imaginary part.

5. Operation of numeric types:

Operator and operator function operation meaning
The sum of X+y x and Y
The difference between x and Y
The product of X*y X and Y
The quotient of x/y and Y
X//y is not greater than the largest integer of the quotient of X and Y
The remainder of the quotient of x%y X and Y
+x x
The negative value of-X x.
X**y X's Y power
Absolute value of ABS (x) x
Divmod (x, y) (x//y,x%y)
Y power of the POW (x, y) x

2. String type:

1. The string is one or more characters enclosed in double quotation marks "" or single quotation marks.

2. Strings can be stored in variables, or they can exist separately

3. The string is a sequence of characters: the leftmost position of the string is marked with 0, which in turn increases.

4. The number in the string is called "index" a particular location in the secondary access string of a single index is formatted as a <string>[< index;]

The string index in 5.Python starts at 0, and the last character of a string with a length of L is L-1,python and allows negative values to be reversed from the right end of the string to the left, and the rightmost index value is-1

6. You can determine a position range by two index values, and return the substring format for this range: <string>[<start>:<end>],start and end are integer values, This subsequence starts at index start until the end of the index ends, but does not include the end position.

7. Most data types can be converted to strings via the STR () function

8. Operation of the string:

+ Connection
* Repeat
<string>[] Index
<string>[:] Cut
Len (<string>) length
<string>.upper () uppercase letters in a string
<string>.lower () lowercase letter in string
<string>.strip () go to both spaces and go to the specified character
<string>.split () splits a string into arrays by a specified character
<string>.join () connecting two string sequences
<string>.find () search for the specified string
<string>.replace () string substitution
For <var> in <string> string iterations

3. Tuple type tuples:

1. Concept:

? A tuple is a type that contains multiple elements, separated by commas. For example: T1 = 123,456, "Hello"

? Tuples can be empty, t2= ()

? When a tuple contains an element: T3=123,

? You can use parentheses outside the tuple, or you can not use the

? Similar to string types, some elements in tuples can be accessed through an index interval. You can use the + sign and the * number between tuples to perform operations

2. Features:

? Elements in a tuple can be of different types; One tuple can also act as an element of another tuple, in which case the tuple of the element needs to be added in parentheses to avoid ambiguity

? Each element in a tuple has a succession relationship, and the elements in the tuple can be accessed through an index

? You cannot change or delete a tuple definition. Code is more secure.

4. List type:

1. Basic Concepts:
? A list is an ordered set of elements;

? A list element can access a single element through an index;

The list size is unlimited and can be modified at any time

2. Operation of the list:

< List1 > + < list2> connection Two listings
< list > * < integer type > Integer repetition of a list
< list > [< integer type;] elements in an indexed list
Number of elements in Len (< seq >) List
< list >[< integer type >: < integer type;] Takes a subsequence of a list
for < var > in < list >: Loop enumeration of lists
< expr > in < list > member check to determine if <expr> is in the list

< list >. Append (x) adds element x to the end of the list
< list >. Sort () Sorts the list elements
< list >. Reverse () reverses the sequence element
< list >. Index () returns the indexed value of the first occurrence of element x
< list >. Insert (i, X) inserts a new element at position I X
< list >. COUNT (x) returns the number of element x in the list
< list >. Remove (x) deletes the first occurrence of an element in the list X
< list >. Pop (i) remove the element of position I from the list and delete it

String, you can split the string into a list by using the split () function, separated by a space by default

5. File types

1. Encoding

? ASCII code:

text files, single-byte, 7-bit, generally English, numeric, and some control characters

? Unicode:
Uniform and unique binary encoding for characters in each language
Two bytes per character long
65,536-character encoded space

UTF-8 encoding
? How variable-length Unicode is implemented
? Chinese three byte representation

GBK encoding
? Double-byte encoding

2. Basic processing of documents

? Open File

The files on the disk are associated with the objects in the program and are obtained through the relevant file objects.

Open ()

<variable> = open (<name>, <mode>)
<name> Disk File name
<mode> Open Mode

Open mode:

R
Read-only. Output error If the file does not exist
W
Write-only (if the file does not exist, the file is created automatically)
A
Indicates the end of the file attached to
Rb
Read only binary files. If the file does not exist, the output
Error
Wb
Writes only the binary file, if the file does not exist, it is automatically
Create a file.
Ab
Append to the end of a binary file
r+
Write

? File operations

Read, write, position, append, COMPUTE, etc.

The read () return value is a string containing the entire file content

ReadLine () returns a string with the value of the next line of the file.

ReadLines () Returns a list of the entire contents of the file, each of which is a line string ending with a newline character.

Write (): Writes a string containing this data or binary data block to the file.

Writelines (): For list operations, accept a list of strings as parameters and write them to the file.

To traverse a file template:

File = open (Somefile, "R")

For line in File[.readlines] ():

#处理一行文件内容

File.close ()

? Close File

Disconnect the file from the program, write to disk, and release the file buffer

Close ()

6. Dictionary type

? The concept of a dictionary
Mapping: The process of finding value information in a collection by any key value
Using a dictionary to implement mappings in Python
A dictionary is a collection of key-value pairs that are indexed by a key and correspond to a value for the same key information
The dictionary type can be keyed with other object types, the data in the dictionary is unordered, and the dictionary type is mapped directly to the value by key

? Operation of the Dictionary

Add an item to a dictionary
Dictionaryname[key] = value

Accessing values in a dictionary
Dictionaryname[key] Returns the value that corresponds to key

Delete an item in the dictionary
Del Dictionaryname[key]

The traversal of a dictionary
For key in students:
Print (Key + ":" + str (Stuendents[key]))

Key to traverse Dictionary
For key in Dictionaryname.keys (): Print. (key)
Traverse Dictionary Values value
For value in Dictionaryname.values (): Print. (value)
To traverse a dictionary item
For item in Dicitonaryname.items (): Print. (item)
Traversing the key-value of a dictionary
For Item,value in Adict.items (): Print (item, value)

Whether a key is in the dictionary in or not

Keys (): Tuple returns a list containing all keys for the dictionary
VALUES (): Tuple returns a list containing all value of the dictionary
Items (): A tuple returns one by one lists containing all key values
Clear (): None removes all items from the dictionary
Get (Key): Value returns the values corresponding to keys in the dictionary
Pop (key): Val deletes and returns the value corresponding to the key in the dictionary
Update (dictionary) adds key values from the dictionary to the Dictionary

8. Turtle Library Math Library and random library:

1. Function Library Reference: 1. The first way: Import < library name > For example: Import turtle If you need to use functions in the library, you need to use the:< library name >.< function name >,2. Second way: from < library name > Import < function name > or from < library name > import * Calling functions do not need < library name, directly using < function name >

2.Turtle Library: A very popular library of drawing images in the Python language

? Forward (distance) #将箭头移到某一指定坐标
? Left (Angel) Right (Angel)
? Penup () #提起笔, used to draw in another place,
Paired with Pendown ()
? goto (x, y)
? Home ()
? Circle (RADIUS)
? Speed ()

3.math Library:

Functions                   meaning
Pi pi          π approximate value, 15 decimal Place
Natural constant e       e approximate value, 15 decimal places
Ceil (x)               The floating-point rounding up
Floo R (x)             The floating point rounding
Pow (x, y)           calculate x y-square
Log (x) &NB Sp             E-based logarithm,
log10 (x)           10-based logarithm,
sqrt (x) &nb Sp           square root

X power of exp (x) E,
Degrees (x) converts the radian value into an angle
radians (x) converts the angle value to radians
Sin (x) sine function
cos (x) cosine function
Tan (x) tangent function
ASIN (x) inverse chord function, x? [ -1.0,1.0]
ACOs (x) inverse cosine function, x? [ -1.0,1.0]

4.random Library:

function meaning
Seed (x) gives the random number a seed value, the default random seed is the system clock, and when the same seed is set, the random number generated after each call to the random function is the same. That's what random seeds do.

Random () generates a randomized decimal between [0, 1.0]
Uniform (A, B) generates a random decimal between A and
Randint (b) generates a random integer between A and B
Randrange (A,B,C) randomly generates a number that increments by C from A to B
Choice (<list>) randomly returns an element from the list
Shuffle (<list>) randomly disrupts elements in the list
Sample (<list>,k) randomly fetches k elements from a specified list

5. Monte Carlo (Monte Carlo) method:

Also known as random sampling or statistical test methods. When the problem solved is the probability of an event, or the expected value of a random variable, it can be solved by some kind of "experiment" method.

Monte Carlo is a method to solve the problem by random experiment, and provides a way to solve the problem by using random number and random experiment in the computer.

9. Control structure:

Three basic structures: sequential structure, selection structure and cyclic structure

1. Select the structure:

1.if Statement format: The statement format is as follows if <condition>:

<body>

? Where <condition> is the conditional expression,<body> is one or more words or multiple statement sequences.? First judge the <condition> condition: true, then execute <body>, and then turn to the next statement, False, skip the <body> directly, and turn to the next statement;

2. The two branch syntax structure is as follows:

If <condition>:

<statements>
Else
<statements>
? The Python interpreter evaluates the <condition> first, and if the <condition> is true, if the following statement is executed, if <condition> is false, else the following statement is executed;
3. Multi-branch decision:

Use If-elif-else to describe multi-branch decisions:? Python evaluates each condition in turn to find a branch that is true and executes the statement under that branch, and if nothing is true, else the statement below is made, and the ELSE clause is optional.

2. Exception Handling:

Try

<body>

except <errertype1>:

except <errertype2>:

[Else:

Finally

When the Python interpreter encounters a try statement, it tries to execute the statement in the body <body> of the Try statement

? If there is no error, control go to the statement after Try-except, execute else statement

? If an error occurs, the Python interpreter looks for an exception statement that matches the error, and then executes the processing code

? Execute the Finally statement whether or not an error occurs

? Else and finally are optional

3. Loop structure:

1.for Cycle
? Python can loop through the values of the entire sequence using a for statement
For <var> in <sequence>:
<body>

? In the For loop, the cyclic variable var iterates through each value in the queue,
The statement body of the ring is executed once for each value.

Range:range (< end >) range (< start number >,< End Count >[,< public ratio;])

The range function is a common function used to create geometric series

The range function has some characteristics:

If the < start number > parameter defaults, the default is 1, and if the < male number > parameter defaults, the default is 0.

. Excluding < end number >,range function returns the number of sequential left-open ([Left,right)]

The. Step parameter must be a non-0 integer or throw a Vauleerror exception.

A For loop is a loop that needs to provide a fixed number of loops

2.while Loop (infinite loop, when type cycle, condition loop, front test loop):

Syntax: While statement
While <condition>:
<body>
3. Note:

Use <CTRL>-C to terminate a program

Break statement-jumps out of the inner For/while loop

Continue statement, which functions as the end of this cycle

<for. Else: ...> <while ... else: ...> statement is used in conjunction with loops, else: After an expression is executed after the For loop list has been traversed or when a while condition statement is not satisfied
4. Cyclic construction method

? Interactive loops

Moredate= "Yes"

While moredate[0]= "Y":

<body>

Moredate=input ("Yes or no?")

? Sentinel Loop

The empty string is represented by "" (no space in the middle of the quotation mark), and can be used as a sentry, and the user enters enter Python to return an empty string

Loop structure Design method that executes loops until a specific value is encountered and the looping statement terminates execution

Xstr=input ("xxx")

While xstr!= "< Sentry >"

<body, operation of the Sentinel >

Xstr=input ("xxx")

? file loops

Line=file.readline ()

While line!= "":

<body, handling each line >

Line=file.readline ()

5. Dead Loop:

Post-test cycle implementation
? Python does not have a post-test loop statement, but can be implemented indirectly through while
? The idea is to design a cyclic condition, directly into the loop body, the cycle is executed at least once, the equivalent of a post-test cycle

Break statements can also be used to implement a post-test loop
? The while statement body executes forever, and if condition determines the loop exits
? In addition: If the body contains only one statement, break can be on the same line as if

Halfway round
? Using Break to exit the loop, the loop exits in the middle of the loop, known as the halfway cycle

6. Boolean expression:

Not>and>or

? The boolean operator for Python is a short-circuit operator

? For numbers (integer and float) 0 values are considered false, any non-0 value is true

? The bool type is just a special integer

? For sequence types, an empty sequence is interpreted as false, and any non-empty sequence is indicated to be true

Attributes of the operator

X and y if x is False,return X,else,return y

X or Y if x is True,return X,else,return y

Not x if X is True,return False,else,return true

ten. Functions

1. Function definition: Using DEF statements
def <name> (<parameters>):
<body>

A function defined by DEF cannot be executed directly in a program without being called, and it needs to be called by a function name to execute

2. Return: Can return any type, one or more. can also not return, equivalent to return none

Return statement: Ends the function call and returns the result to the caller
? The return statement is optional and can appear anywhere in the body of the function
? Without a return statement, the function returns control to the caller at the end of the function body
3. Parameter values

The parameter of the function receives only the value of the argument, and the parameter assignment does not affect the argument

The function cannot modify the variable itself, and if the variable is a mutable object (such as a list or drawing object), the object renders the modified state after it is returned to the calling program.

4. Recursion

Recursive definition features:
? There is one or more of the basic examples that do not need to be recursively recursive;

? All recursion chains end with a single base example.

? After 900 calls, the default "maximum recursive depth" is reached, terminating the call

5. Example Turtle Painting tree: http://www.cnblogs.com/Wang-Y/p/8444889.html



Python syntax elements

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.