Perfect Python Primer Basics Summary

Source: Internet
Author: User
Tags abs arithmetic arithmetic operators bitwise ord square root terminates python list

Python identifiers

In Python, identifiers are composed of letters, numbers, and underscores.

In Python, all identifiers can include English, numeric, and underscore (_), but cannot begin with a number.

Identifiers in Python are case-sensitive.

Identifiers that begin with an underscore are of special significance. A class attribute that begins with a single underscore, which is not directly accessible by the _foo, must be accessed through the interface provided by the class and cannot be imported with the From XXX import *;

A __foo that begins with a double underscore represents a private member of a class; A __foo__ that begins and ends with a double underscore represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class.

Python has five standard data types

Numbers (digital)

String (String)

List (lists)

Tuple (tuple)

Dictionary (dictionary)

Python supports four different types of numbers

int (signed integral type)

Long (longer integer [can also represent octal and hexadecimal])

Float (float type)

Complex (plural)

Python List of strings has 2 order of values

Left-to-right index starts at default 0, with a maximum range of 1 less string lengths

Right-to-left index starts with default-1, the maximum range is the beginning of the string

List is the most frequently used data type in Python

A list can accomplish the data structure implementation of most collection classes. It supports characters, numbers, and strings that can even contain lists (that is, nesting).

The list is identified by [], which is the most common type of composite data for Python.

The cut of the value in the list can also be used to the variable [head subscript: Tail subscript], you can intercept the corresponding list, from left to right index default 0, starting from right to left index default-1, subscript can be empty to take the head or tail.

The plus + is the list join operator, and the asterisk * is a repeating operation.

Tuples are another data type, similar to list

The tuple is identified with a "()". The inner elements are separated by commas. However, tuples cannot be assigned two times, which is equivalent to a read-only list.

Dictionary (dictionary) is the most flexible built-in data structure type in Python except for lists

A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

The dictionary is identified with "{}". A dictionary consists of an index (key) and a value corresponding to it.

Python Data type conversions

Sometimes, we need to convert the data-built type into the data type, and you just need to use the data type as the function name.

The following several built-in functions can perform conversions between data types. These functions return a new object that represents the value of the transformation.

Function description

int (x [, Base]) converts x to an integer

Long (x [, Base]) converts x to a long integer

Float (x) converts x to a floating-point number

Complex (real [, Imag]) creates a complex number

STR (x) converts an object x to a string

REPR (x) converts an object x to an expression string

Eval (str) is used to calculate a valid Python expression in a string and returns an object

Tuple (s) converts a sequence s to a tuple

List (s) converts the sequence s to a list

Set (s) is converted to a mutable set

Dict (d) Create a dictionary. D must be a sequence (key,value) tuple.

Frozenset (s) converted to immutable collection

Chr (x) converts an integer to one character

UNICHR (x) converts an integer to a Unicode character

Ord (x) converts a character to its integer value

Hex (x) converts an integer to a hexadecimal string

Oct (x) converts an integer to an octal string

Python operators

Arithmetic operators

Compare (relational) operators

Assignment operators

logical operators

Bitwise operators

Member operators

Identity operator

Operator Precedence

Python arithmetic operators

Operator Description Instance

+ Plus-two objects add a + B output result 30

-minus-get negative numbers or one number minus another number A-B output result-10

* Multiply by two numbers or return a string that is repeated several times a * b output result 200

/divide-X divided by yb/a output 2

% modulo-Returns the remainder of division B% A output result 0

* * Power-Returns the Y power of x a**b to 10 20, output 100000000000000000000

Divide-Returns the integer portion of the quotient 9//2 output result 4, 9.0//2.0 output 4.0

Python comparison operators

The following assumes that the variable A is 10 and the variable B is 20:

Operator Description Instance

= = equals-The comparison object is equal (a = = B) returns FALSE.

! = does not equal-compares two objects that are not equal (a! = B) returns TRUE.

<> not equals-compares two objects for unequal (a <> B) returns True. This operator is similar to! =.

> Greater-Returns FALSE if X is greater than Y (a > B).

< less-Returns whether x is less than Y. All comparison operators return 1 for true, and return 0 for false. This distinction is equivalent to the special variable true and false. Note that these variable names are capitalized. (A < B) returns TRUE.

>= is greater than or equal-returns whether X is greater than or equal to Y. (a >= B) returns FALSE.

<= is less than or equal-returns whether X is less than or equal to Y. (a <= B) returns True.

Python assignment operator

The following assumes that the variable A is 10 and the variable B is 20:

Operator Description Instance

= Simple assignment Operator C = A + B assigns the result of the operation of A + B to c

+ = addition Assignment operator C + = A is equivalent to C = C + A

-= Subtraction Assignment operator C-= A is equivalent to C = c-a

*= multiplication assignment operator C *= A is equivalent to C = c * A

/= Division assignment operator C/= A is equivalent to C = c/a

%= modulo assignment operator C%= A is equivalent to C = c% A

**= Power assignment operator C **= A is equivalent to C = c * * A

= Take divisible assignment operator C//= A is equivalent to C = c//A

Python bitwise operators

The variable a in the following table is 60,b 13 and the binary format is as follows:

A = 0011 1100b = 0000 1101-----------------A&b = 0000 1100a|b = 0011 1101a^b = 0011 0001~a = 1100 0011

Operator Description Instance

& Bitwise AND Operator: Two values that participate in the operation, if two corresponding bits are 1, the result of that bit is 1, otherwise 0 (A & B) outputs 12, binary interpretation: 0000 1100

| bitwise OR operator: As long as the corresponding two binary has one for 1 o'clock, the result bit is 1. (A | b) output result 61, Binary interpretation: 0011 1101

^ Bitwise XOR Operator: When two corresponding binary differences, the result is 1 (a ^ b) output result 49, binary interpretation: 0011 0001

~ Bitwise inverse Operator: bits for each of the data, i.e. 1 to 0, 0 to 1 (~a) output-61, Binary interpretation: 1100 0011, in the complement form of a signed binary number.

<< left move operator: Each binary of the operand all shifts left several bits, the number of "<<" to the right to specify the number of bits moved, high drop, low 0. A << 2 output results 240, binary interpretation: 1111 0000

>> Right Move operator: All the binary of the left operand of ">>" is shifted to the right of a number of bits, the number to the right of ">>" specifies the number of bits moved a >> 2 output result 15, binary interpretation: 0000 1111

Python logical operators

The Python language supports logical operators, with the following assumption that the variable A is ten and B is 20:

Operator logical expression describes an instance

AndX and Y Boolean "and"-if x is False,x and y returns FALSE, otherwise it returns the computed value of Y. (A and B) returns 20.

Orx or Y Boolean "or"-if X is non-0, it returns the value of x, otherwise it returns the computed value of Y. (A or B) returns 10.

Notnot x boolean "Non"-returns False if X is True. If X is False, it returns TRUE. Not (A and B) returns False

Python member operators

In addition to some of the above operators, Python also supports member operators, which contain a series of members, including strings, lists, or tuples.

Operator Description Instance

In if the value found in the specified sequence returns TRUE, False is returned. x in the y sequence, if X returns True in the y sequence.

Not if no value is found in the specified sequence returns True, otherwise False is returned. X is not in the Y sequence if x does not return True in the y sequence.

Python identity operator

The identity operator is used to compare the storage units of two objects

Operator Description Instance

ISIS is to determine whether two identifiers are referenced from an object x is Y, similar to ID (x) = = ID (y), and returns True if the reference is the same object, otherwise False

is Notis does not determine whether two identifiers are referenced from a different object x is not y, similar to ID (a)! = ID (b). Returns True if the reference is not the same object, otherwise False is returned.

Note: IS and = = difference:

is used to determine whether the two variables refer to the same object, = = is used to determine whether the value of the reference variable is equal.

Python Loop statement

Python provides a For loop and a while loop (there is no do in Python: While loop):

Circular type description

The while loop executes the loop body when the given judgment condition is true, otherwise exits the loop body.

The For loop repeats the execution of the statement

Nested loops you can nest for loops in the while loop body

loop control statements can change the order in which statements are executed. Python supports the following loop control statements:

Control Statement Description

The break statement terminates the loop during the execution of the statement block and jumps out of the entire loop

The continue statement terminates the current loop during the execution of the statement block, jumps out of the loop, and executes the next loop.

Pass Statement Pass is an empty statement in order to maintain the integrity of the program structure.

Python Number (numeric)

Python supports four different numeric types:

Integer (INT)-usually referred to as an integer or integral, is a positive or negative integer, with no decimal points.

Long integers-an integer with an infinite size, and an integer that ends with an uppercase or lowercase L.

Float (floating point real values)-floating-point types consist of integral and fractional parts, and floating-point types can also be represented using scientific notation (2.5e2 = 2.5 x 102 = 250)

Complex numbers (complex numbers)-complex numbers are made up of real and imaginary parts, and can be represented by a + BJ, or complex (A, a, b), where both the real and imaginary part of a complex number are floating-point types.

Note: Long integers can also use lowercase "l", but it is recommended that you use uppercase "L" to avoid confusion with the number "1". Python uses "L" to display the long integer type.

Python also supports complex numbers, which consist of real and imaginary parts, and can be represented by a + BJ, or complex (a, b), where the real and imaginary parts of a complex number are floating-point

Python Number Type Conversion

int (x [, Base]) converts x to an integer

Long (x [, Base]) converts x to a long integer

Float (x) converts x to a floating-point number

Complex (real [, Imag]) creates a complex number

STR (x) converts an object x to a string

REPR (x) converts an object x to an expression string

Eval (str) is used to calculate a valid Python expression in a string and returns an object

Tuple (s) converts a sequence s to a tuple

List (s) converts the sequence s to a list

Chr (x) converts an integer to one character

UNICHR (x) converts an integer to a Unicode character

Ord (x) converts a character to its integer value

Hex (x) converts an integer to a hexadecimal string

Oct (x) converts an integer to an octal string

Python math functions

function return value (description)

ABS (x) returns the absolute value of the number, such as ABS (-10) returns 10

Ceil (x) returns the top integer of a number, such as Math.ceil (4.1) returns 5

CMP (x, y) if x < y returns 1, if x = = y returns 0, if x > y returns 1

EXP (x) returns the x power of E (ex), such as MATH.EXP (1) returns 2.718281828459045

Fabs (x) returns the absolute value of a number, such as Math.fabs (-10) returns 10.0

Floor (x) returns the lower integer of the number, such as Math.floor (4.9) returns 4

Log (x) as Math.log (MATH.E) returns 1.0,math.log (100,10) returns 2.0

LOG10 (x) returns the logarithm of x with a base of 10, such as MATH.LOG10 (100) returns 2.0

Max (x1, x2,...) Returns the maximum value of a given parameter, which can be a sequence.

Min (x1, x2,...) Returns the minimum value for a given parameter, which can be a sequence.

MODF (x) returns the integer part and fractional part of X, the two-part numeric symbol is the same as x, and the integer part is represented by a floating-point type.

Pow (x, y) the value after the x**y operation.

Round (x [, N]) returns the rounding value of the floating-point number x, given the n value, which represents the digits rounded to the decimal point.

SQRT (x) returns the square root of the number x, the number can be negative, and the return type is real, such as MATH.SQRT (4) returns 2+0J

Python random function

Random numbers can be used in mathematics, games, security and other fields, but also often embedded in the algorithm to improve the efficiency of the algorithm and improve the security of the program.

Python contains the following common random number functions

Function description

Choice (seq) randomly picks an element from a sequence of elements, such as Random.choice (range (10)), and randomly picks an integer from 0 to 9.

Randrange ([Start,] stop [, step]) gets a random number from the specified range, in the collection incremented by the specified cardinality, and the base default value is 1

Random () randomly generates the next real number, which is within the range of [0,1].

Seed ([x]) changes the seeding seed of the random number generator. If you don't know how it works, you don't have to specifically set Seed,python to help you choose Seed.

Shuffle (LST) randomly sorts all elements of a sequence

Uniform (x, y) randomly generates the next real number, which is within the [x, Y] range.

Python Trigonometric functions

Python includes the following trigonometric functions

Function description

ACOs (x) returns the inverse cosine radian value of x.

ASIN (x) returns the arc value of the sine of X.

Atan (x) returns the arc tangent value of x.

Atan2 (y, x) returns the inverse tangent value of the given x and Y coordinate values.

COS (x) returns the cosine of the arc of X.

Hypot (x, y) returns Euclidean norm sqrt (x*x + y*y).

Sin (x) returns the sinusoidal value of the X-arc.

Tan (x) returns the tangent of x radians.

Degrees (x) converts radians to angles, such as degrees (MATH.PI/2), returns 90.0

radians (x) converts an angle to radians

Python Math Constants

Constant description

Pi Mathematical constant Pi (pi, usually denoted by π)

e mathematical constants E,e i.e. natural constants (natural constants).

Python string

Python escape character

Python uses a backslash () to escape characters when you need to use special characters in characters.

As the following table:

Escape Character Description

Line continuation (at end of row)

\ backslash Symbol

' Single quotation mark

"Double quotation marks

A bell

BACKSPACE (Backspace)

E escape

Empty

Line break

Portrait tab

Horizontal tab

Enter

Page change

Oyy octal number, yy represents the character, for example: O12 represents a newline

\XYY hexadecimal number, yy represents the character, for example: \x0a represents a newline

Other characters are output in normal format

Python string operator

The following table instance variable a value is the string "Hello" and the B variable value is "Python"

Operator Description Instance

+ String Connection >>>a + B ' Hellopython '

* Repeat output string >>>a * 2 ' Hellohello '

[] Get the characters in the string by index >>>a[1] ' e '

[:] Intercept part of the string >>>a[1:4] ' ell '

In member operator-if the string contains the given character return true>>> "H" inatrue

Not in member operator-returns true>>> "M" if the string does not contain the given character notinatrue

R/R Raw String-Raw string: all strings are used directly as literal meanings, without escaping special or non-printable characters. The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter "R" (which can be case). >>>printr ' >>> printr '

% format string See next section

Python string formatting

Python supports the output of formatted strings. Although this may use a very complex expression, the most basic usage is to insert a value into a string that has the string format of%s.

In Python, string formatting uses the same syntax as the sprintf function in C.

The following example:

#!/usr/bin/pythonprint "My name is%s and weight is%d kg!"% (' Zara ', 21)

The result of the above example output:

My name is Zara and weight are kg!

Python string formatting symbols:

Symbol description

%c formatted character and its ASCII code

%s formatted string

%d formatted integer

%u format unsigned integer

%o Formatting an unsigned octal number

%x format unsigned hexadecimal number

%x format unsigned hexadecimal number (uppercase)

%f formatting floating-point numbers to specify the precision after the decimal point

%e format floating-point numbers with scientific notation

%E function with%E, format floating-point numbers with scientific notation

Shorthand for%g%f and%e

Shorthand for%G%f and%E

%p the address of a variable with hexadecimal number format

Python list

Python contains the following functions:

ordinal function

1CMP (List1, List2)

Compare two elements of a list

2len (list)

Number of list elements

3max (list)

Returns the maximum value of a list element

4min (list)

Returns the minimum value of a list element

5list (seq)

Convert a tuple to a list

Python contains the following methods

Ordinal method

1list.append (obj)

Add a new object at the end of the list

2list.count (obj)

Count the number of occurrences of an element in a list

3list.extend (seq)

Append multiple values from another sequence at the end of the list (extend the original list with a new list)

4list.index (obj)

Find the index position of the first occurrence of a value from the list

5list.insert (index, obj)

Inserting an object into a list

6list.pop (Obj=list[-1])

Removes an element from the list (the last element by default), and returns the value of the element

7list.remove (obj)

To remove the first occurrence of a value in a list

8list.reverse ()

Reverse List of elements

9list.sort ([func])

Sort the original list

Python tuples

A python tuple (tuple) is similar to a list, except that the elements of a tuple cannot be modified.

Tuples use parentheses, and the list uses square brackets.

Tuple built-in functions:

The Python tuple contains the following built-in functions

Ordinal method and Description

1CMP (Tuple1, Tuple2)

Compares two tuples of elements.

2len (tuple)

Counts the number of tuple elements.

3max (tuple)

Returns the element's maximum value in a tuple.

4min (tuple)

Returns the element minimum value in a tuple.

5tuple (seq)

Converts a list to a tuple.

Python Dictionary (dictionary)

A dictionary is another mutable container model and can store any type of object.

Each key value of the dictionary (key=>value) pairs with a colon (:) split, each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({})

Dictionary built-in functions and methods:

The Python dictionary contains the following built-in functions:

ordinal function and description

1CMP (Dict1, Dict2)

Compares two dictionary elements.

2len (Dict)

Calculates the number of dictionary elements, that is, the total number of keys.

3str (Dict)

The output dictionary is a printable string representation.

4type (variable)

Returns the type of the variable entered and returns the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in methods:

ordinal function and description

1dict.clear ()

Delete all elements in a dictionary

2dict.copy ()

Returns a shallow copy of a dictionary

3dict.fromkeys (seq[, Val]))

Create a new dictionary with the keys to the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary

4dict.get (Key, Default=none)

Returns the value of the specified key if the value does not return the default value in the dictionary

5dict.has_key (Key)

Returns False if the key returns true in the dictionary Dict

6dict.items ()

Returns an array of traversed (key, value) tuples as a list

7dict.keys ()

Returns a dictionary of all keys in a list

8dict.setdefault (Key, Default=none)

Similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to default

9dict.update (DICT2)

Update the key/value pairs of the dictionary dict2 to the Dict

10dict.values ()

Returns all values in the dictionary as a list

11pop (Key[,default])

Deletes the value of the dictionary given key key, and returns the value to be deleted. The key value must be given. Otherwise, the default value is returned.

12popitem ()

Randomly returns and deletes a pair of keys and values in the dictionary.

anonymous function lambda

Python uses lambda to create anonymous functions.

Lambda is just an expression, and the function body is much simpler than def.

The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.

The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.

Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.

Such as:

Sum =lambda arg1, ARG2:ARG1 + arg2;print "added value is:", sum (10,20)//Output 30

Python import statement

From...import statements

The FROM statement of Python lets you import a specified section from the module into the current namespace. The syntax is as follows:

From ModName import name1[, name2[, ... Namen]]

For example, to import the Fibonacci function of a module FIB, use the following statement:

From fib import Fibonacci

This declaration does not import the entire FIB module into the current namespace, it only introduces the Fibonacci individual in the FIB to the global symbol table of the module that executes the declaration.

from...import* statements

It is also possible to import all the contents of a module into the current namespace, just use the following declaration:

From ModName Import *

This provides an easy way to import all the items in a module. However, such statements should not be used too much.

For example, we want to introduce all the things in the math module at once, with the following statements:

From Math import*

Python file operations

Opening and closing files

You can now read and write to standard inputs and outputs. Now, let's see how to read and write actual data files.

Python provides the necessary functions and methods for basic file operation by default. You can use the file object to do most of the document operations.

Open function

You must first open a file with the Python built-in open () function, create a Document object, and the related method can call it for read and write.

Grammar:

File Object = open (file_name [, access_mode][, Buffering])

The details of each parameter are as follows:

The File_name:file_name variable is a string value that contains the name of the file you want to access.

Access_mode:access_mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).

Buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.

Full list of open files in different modes:

Pattern description

R opens the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default mode.

RB opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.

r+ open a file for read-write. The file pointer will be placed at the beginning of the file.

rb+ opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file.

W opens a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.

WB opens a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.

w+ open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.

wb+ opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.

A opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.

AB opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.

A + opens a file for read and write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.

ab+ opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.

Properties of the File object

After a file is opened, you have a files object that you can get various information about the file.

The following is a list of all properties related to the file object:

Property Description

File.closed returns True if the file has been closed, otherwise false is returned.

File.mode returns the access mode of the file being opened.

File.name returns the name of the file.

File.softspace if the print output must be followed by a space character, false is returned. Otherwise, returns True.

Close () method

The close () method of the file object flushes any information that has not yet been written in the buffer and closes the file, which can no longer be written.

When a reference to a file object is re-assigned to another file, Python closes the previous file. Closing a file with the close () method is a good habit.

Grammar:

Fileobject.close ();

Write () method

The write () method writes any string to an open file. It is important to note that the Python string can be binary data, not just text.

The Write () method does not add a line break (') at the end of the string:

Grammar:

Fileobject.write (string);

Read () method

The Read () method reads a string from an open file. It is important to note that the Python string can be binary data, not just text.

Grammar:

Fileobject.read ([count]);

File location

The tell () method tells you the current position within the file, in other words, the next read and write occurs after so many bytes at the beginning of the file.

The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.

If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be used as the reference location.

Renaming and deleting files

Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.

To use this module, you must first import it before you can invoke the various functions associated with it.

Remove method

You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.

The directory in Python

All files are contained in different directories, but Python is also easy to handle. The OS module has many ways to help you create, delete, and change directories.

mkdir () method

You can use the mkdir () method of the OS module to create new catalogs in the current directory. You need to provide a parameter that contains the name of the directory you want to create.

Grammar:

Os.mkdir ("Newdir")

ChDir () method

You can use the ChDir () method to change the current directory. The ChDir () method requires a parameter that you want to set as the directory name of the current directory.

Grammar:

Os.chdir ("Newdir")

RmDir () method

The RmDir () method deletes the directory, and the directory name is passed as a parameter.

Before deleting this directory, all of its contents should be purged first.

Grammar:

Os.rmdir (' dirname ')

File and directory related methods

Three important method sources can be used for a wide and practical processing and manipulation of files and directories on Windows and UNIX operating systems, as follows:

File Object method: The File object provides a series of methods for manipulating files.

OS Object methods: Provides a series of methods for working with files and directories.

Python file (file) method

The file object is created using the Open function, and the following table lists the functions commonly used by file objects:

Ordinal method and Description

1file.close ()

Close the file. The file can no longer read and write after closing.

2file.flush ()

Refreshes the file internal buffer, directly writes the internal buffer data immediately to the file, rather than passively waits for the output buffer to write.

3file.fileno ()

Returns an integer that is a file descriptor (Descriptor FD Integer) that can be used in some of the underlying operations, such as the Read method of the OS module.

4file.isatty ()

Returns True if the file is connected to an end device, otherwise False is returned.

5file.next ()

Returns the next line of the file.

6file.read ([size])

Reads the specified number of bytes from the file, if none is given or is negative.

7file.readline ([size])

Reads the entire line, including the "" character.

8file.readlines ([Sizehint])

Reads all rows and returns a list, and if given sizeint>0, returns a row with a sum of approximately sizeint bytes, the actual read value may be larger than sizhint because the buffer needs to be populated.

9file.seek (offset[, whence])

Set the current location of the file

10file.tell ()

Returns the current location of the file.

11file.truncate ([size])

Intercepts the file, the truncated byte is specified by size, and the default is the current file location.

12file.write (str)

Writes a string to the file without a return value.

13file.writelines (Sequence)

Writes a list of sequence strings to the file and adds a newline character to each line if a line break is required.

Python built-in functions

Built-in functions

ABS () divmod () input () open () Staticmethod ()

All () enumerate () int () ord () str ()

Any () eval () isinstance () Pow () sum ()

Basestring () execfile () Issubclass () print () Super ()

Bin () file () ITER () property () tuple ()

BOOL () filter () Len () range () type ()

ByteArray () float () list () Raw_input () UNICHR ()

Callable () format () locals () reduce () Unicode ()

Chr () Frozenset () long () reload () VARs ()

Classmethod () GetAttr () map () repr () xrange ()

CMP () Globals () Max () reversed () Zip ()

Compile () hasattr () Memoryview () round () __import__ ()

Complex () hash () min () set ()

Delattr () Help () Next () SetAttr ()

Dict () Hex () object () slice ()

DIR () ID () Oct () sorted () exec built-in expression

Like friends can add QQ group 813622576, the group has free information for everyone to Exchange learning Oh!!

Webmaster Statistics

Perfect Python Primer Basics Summary

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.