Python basics (file input/output built-in dictionary operations)

Source: Internet
Author: User
Tags element groups natural string
This article mainly introduces the basics of python, including file input and output, built-in types, dictionary operations, and other usage methods. I. variables and expressions

The code is as follows:


>>> 1 + 1
2
>>> Print 'Hello world'
Hello world
>>> X = 1
>>> Y = 2
>>> X + y
3

Python is a strongly typed language and cannot be automatically parsed and converted to a suitable type based on the context. Python is a dynamic language. during the program running, the same variable name can represent different values (integer, floating point, list, and tuples) at different stages of the program running ), variable names are only references to various types of data and objects. The variable name in C language is the memory segment used to store the results.

1. in Python, values are assigned to variables through object references rather than values.

2. the value assignment operator is mainly "=", and incremental value assignment can also be used, for example, x + = 1. However, there are no auto-increment or auto-subtraction operators.

3. in C, the value assignment statement can be used as an expression (which can return values), but in Python, the value assignment statement does not return values. the following statements are invalid:

The code is as follows:


>>> X = 1
>>> Y = (x = x + 1)

SyntaxError: invalid syntax
To #! The line at the beginning is called an organizational line. this line tells your Linux/Unix system which interpreter should be run when you execute your program. Example :#! /Usr/bin/python

A comment line starts.

II. conditional statements

Control flow statement: any conditional expression can be created by using the or, and, not keyword.

If-elif-else :( Python does not have a switch-case statement. you can use the if statement in combination with the dictionary to do the same job)

The code is as follows:


If something = 1:
DoSomething1 ()
Elif something = 2:
DoSomething2 ()
Else:
Pass # indicates an empty block or an empty body. use the pass statement.
While-else:
While something:
DoSomething1 ()
Else:
DoSomething2 ()
For-else:
For I in range (1, 10, 2): # The I value ranges from 1 to 10 and the step size is 2.
Print I
Else:
Print 'The for loop is over'

Break and continue: used to interrupt and continue the loop.

3. file input/output

The code is as follows:


F = open ("foo.txt ")
Line = f. readline ()
While line:
Print line,
Line = f. readline () # read a row, including the line break '\ n'. when the end of the file is read, an empty string is returned.
F. close ()

F = open ("out.txt", "w ")
Year = 1
Money = 1000.
While year <= 5:
Money = money * (1 + 0.05)
F. write ("% 3d % 0.2f \ n" % (year, money) # print> f, "% 3d % 0.2f" % (year, money)
Year + = 1
F. close ()

For line in f. xreadlines ():
# Do something with line

IV. built-in types

4.1 None type

None indicates an empty object. If no value is returned for a function, None is returned. The bool value of None is false.

4.2 value type

Python has four numeric types: integer, long integer, floating point, and plural. All value types are unchangeable.

Python does not support the auto-increment and auto-increment operators ++, --, ++ I, which actually means ++ (+ I ).

Operators and expressions: they are basically similar to other languages, except for the following differences:

X * y: multiplication. 2*3 get 6. 'La '* 3 to get 'Lala '.
X ** y: power operation, returns the y power of x.
X/y: divide x by y, and 4/3 to get 1 (the integer result is obtained by division of integers ). 4.0/3 or 4/3. 0 is 1.3333333333333333.
X // y: returns the integer division. Returns the integer part of the operator. 4 // 3.0 get 1.0.
Division //: place the fractional part of the floor to 0 at any time.
-X changes the symbol bit of x.

4.3 string
String: single quotation marks (') and double quotation marks (") have the same effect. you can only create single-line strings. The escape character is (\).

Everything between three quotation marks (for example, ''' or "") is the content of a string.

Natural string: Add R (or r) before the string to indicate certain strings that do not require special processing such as escape characters, such as print R "Hello \ n World ", "Hello \ n World" will be output directly without line breaks.

The code is as follows:


A = "hello world"
B = a [0, 5] # B = "hello"
C = a + "I love you" # c = "hello world I love you"
S = "The value of x is" + str (x)


Returns the substring from I to j (excluding j. If I is omitted, I = 0. if j is omitted, j = len (s)-1

The str () repr () function or the backward quotation mark (') can convert other types of data into strings.

Unicode string: add U (or u) before the string ). For example, if a = u 'hello', each character is expressed as "hello" 'world' in 16 bits, it is automatically connected to a string "helloworld ", "s1" u "s2" will generate u "s1s2"

String, Unicode string, and tuple are immutable sequences.

4.4 list and metadata (list & tuple)

Lists and element groups are the sequences of arbitrary objects. common operations are supported:

The code is as follows:


Len ()
Append ()
Insert (index, aMember)
List [index] = aNewMember

The tuples of an element: a = (12,) # note that an additional comma is required!
Elements in tuple cannot be modified or added.
The list is a variable sequence, allowing you to insert, delete, or replace elements.

Operations supported by the variable sequence:

The code is as follows:


S [I] = v
S [I: j] = t # t is a sequence.
Del s [I]
Del s [I: j]

4.5 Dictionary

A dictionary is an associated array (or a hash table). It is a collection of objects indexed by keywords.

Use {} to create a dictionary

The code is as follows:


A = {
"Username": "loo"
"Home": "/home/loo"
"Uid": 500
}
U = a ["username"] # access
A ["username"] = "lu" # Modify
A ["shell"] = "/usr/bin/tcsh" # Add
Del a ["shell"] # Delete
Len (a) # Number of elements
A [("loo", 123)] = "abc"

The dictionary key is an object that cannot be modified (such as numbers and tuple ).

V. Loop

The code is as follows:


For I in range (1, 5 ):
Print "2 to the % d power is % d" % (I, 2 ** I)


The built-in function range ([I,] j [, stride]) creates a list. parameter I and parameter stride are optional. the default values are 0 and 1.

The code is as follows:


A = range (5, 1,-1) # a = [5, 4, 3, 2]
S = "hello world"
For c in s: # print each character
Print c


The range () function creates a list in the memory. when a large list is required, this occupies memory and consumes time. to overcome this disadvantage, python provides xrange (). The xrange () function temporarily calculates the provided value only when needed, greatly saving the memory.

VI. Functions

Def say (message, times = 1): # The default value of time is 1.
Print message * times
Return time # functions without return values can save return, which is equivalent to return None.
Only those parameters at the end of the parameter table can have default parameter values. that is, when you cannot declare a function parameter, you must first declare a parameter with the default value and then declare a parameter without the default value. This is because the value assigned to the form parameter is assigned based on the position. For example, def func (a, B = 5) is valid,

However, def func (a = 5, B) is invalid.

Global a # obtain global variable

User-defined functions:

The code is as follows:


Def foo (x, y ):
Print '% s + % s is % s' % (str (x), str (y), str (x + y ))
Bar = foo
Bar (3, 4)
D = {}
D ['callback'] = foo
D ['callback'] (3, 4) # Call foo

User-defined functions have the following attributes:

F. _ module _ # module name of the function
F. _ doc _ or f. func_doc # document string
F. _ name _ or f. func_name # function name
F. _ dict _ or f. func_dict # function namespace supporting any function attribute
F. func_code # bytecode generated after Compilation
F. func_defaults # tuples containing all default parameters
F. func_globals # Dictionary of the global namespace of the module where the function is located
F. func_closure # None or a tuple of cells that contain bindings for the function's free variables.

VII. Category

The code is as follows:


Class Stack (object ):
Def _ init _ (self ):
Self. stack = []
Def push (self, object ):
Self. stack. append (object)
Def pop (self ):
Return self. stack. pop ()
Def length (self ):
Return len (self. stack)
S = Stack ()
S. push ("Dave ")
S. push (42)
S. push ([3, 4, 5])
Print s. length ()
Print s. pop ()
Y = s. pop ()
Print y
Del s

Class method definition:

The code is as follows:


# Static method:
Class AClass (object ):
@ Staticmethod
Def astatic ():
Print 'a static method'
# Class method:
Class ABase (object ):
@ Classmethod
Def aclassmethod (cls ):


Isinstance (s, C) is used to test whether s is an instance of the C or C subclass.
Issubclass (A, B) is used to test whether A is A subclass of B.

8. Exceptions

Use the try and retry T statements to capture exceptions:

The code is as follows:


Try:
F = open ("file.txt", "r ")
Handle T IOError, e:
Print e
Failed T TypeError, e:
Print e
...
Try:
Do something
Except t:
Print 'a error occurred'

If there is an IOError exception, place the cause of the error in object e, and then run the handle T code block. if there are other types of exceptions, the control will be transferred to the blocks that handle the exception, if the code block is not found, the program stops running. If no exception occurs, wait t
The code is ignored.

9. module

Import module name
Import module name as Alias
From module import object (function)
From module import *
The built-in function dir () can list all accessible content in a module.
Modules that can be imported by import:
1. programs written in python (. py program)
2. C or C ++ extensions (compiled shared libraries or DLL)
3. package (including multiple modules)
4. built-in modules (written in C and linked to the python interpreter)

10. reference and copy (reference count)

All data in python is an object.
For a mutable object, changing a reference is equivalent to changing all references of the object:

The code is as follows:


A = [1, 2, 4]
B =
B [2] = 100
Print a # a = [,]


To avoid this situation, you need to create a copy of the variable object and then operate on the copy.

There are two ways to create a copy of a mutable object:

(1) shallow copy: creates a new object, but its child elements are still referenced by the child elements of the original object:

The code is as follows:


B = [1, 2, 4]
A = B [:]
A. append (1, 100)
Print B # B = [1, 2, [3, 4] B not changed
A [0] = 100
Print B # B = [1, 2, [3, 4] B not changed
A [2] [0] = 100
Print B # B = [, [] B is changed

(2) deep copy)

The code is as follows:


Import copy
B = [1, 2, 4]
A = copy. deepcopy (B)


_ Del _ () is called when the object is destroyed. Del x only reduces the reference count of object x and does not call this function.

11. type conversion

The code is as follows:


Int (x [, base]) # Convert to int
Long (x [, base])
Float (x)
Tuple (x)
List (x)
Chr (x) # Convert to character
Unichr (x) # Convert to Unicode
Ord (x) # converts a character to an integer
Str (x)
A = [1, 2, 4]
S = repr (a) # s = '[1, 2, 3, 4]' can also use s = 'A'
B = eval (s) # B = [1, 2, 3, 4] and then convert it into a list.
Eval ('3 + 4 ')
F = open ("foo ")
A = repr (f) # a =" "

12. others

DocStrings: If the first statement of a module, class, or function body is an untitled string, the modified string will automatically become the document string of this object. to put it bluntly, it is something similar to JavaDoc.

A document string is a multi-line string whose first line starts with an uppercase letter and ends with a full stop. The second line is empty, and the detailed description starts from the third line. You can use _ doc _ (pay attention to double underscores) to call the document string attribute of a function (belongs to the function name ). Python regards everything as an object, including this function.

In Python, help () only captures the _ doc _ attribute of the function, and then shows it to you neatly.

Automated tools can also extract documents from your programs in the same way. The pydoc command that comes with the Python release is similar to help () using DocStrings.

The code is as follows:


Def printMax (x, y ):
'''Prints the maximum of two numbers. ''' # Here is the document string
Print "DocStrings" # Here is the function body command line parameter
>>> Print printMax. _ doc __
Prints the maximum of two numbers.


Id (a) allows you to view the id of the object (the current implementation is the location of the object in the memory)

The code is as follows:


If type (a) is type (B ):
Print 'a and B have the same type'
If type (a) is types. ListType
Print 'is a list'


Isinstance (s, C) is used to test whether s is an instance of the C or C subclass.

The code is as follows:


Import types
Isinstance (3, types. IntType) # return True


X = y compare whether the values of x and y are equal
X is y and x is not y compare whether x and y point to the same object in memory

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.