Introduction to Python Basics (file input/output built-in type dictionary operation usage) _python

Source: Internet
Author: User
Tags case statement eval numeric natural string readline shallow copy in python

A, variable, and an expression

Copy Code code 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 converted to a suitable type based on context automatic parsing. Python is a dynamic language in which the same variable name can represent different types of values (integer, float, list, tuple) at different stages of operation, and variable names are just references to various data and objects. The variable name in the C language is the memory fragment that holds the result.

1. In Python, you assign values to variables by reference to an object rather than by a value.

2, the assignment operator is mainly "=", but also can use incremental assignment, such as X+=1. But there is no self increasing, self subtraction operator.

3. In C, an assignment statement can be used as an expression (you can return a value), but the assignment statement in Python does not return a value, as the following is illegal:

Copy Code code as follows:

>>> x=1
>>> y= (x=x+1)

Syntaxerror:invalid syntax
With #! The beginning is called the organization line, which tells you which interpreter the Linux/unix system should run when you execute your program. For example: #!/usr/bin/python

The beginning of a # is called a comment line.

Second, conditional statements

Control Flow statement: Any conditional expression can be established by using the Or,and,not keyword

If-elif-else: (Python does not have the Switch-case statement, you can do the same work with the dictionary through the IF statement)

Copy Code code as follows:

If something = 1:
DoSomething1 ()
elif something = = 2:
DoSomething2 ()
Else
Pass # represents an empty block or an empty body, using the PASS statement
While-else:
While something:
DoSomething1 ()
Else
DoSomething2 ()
For-else:
For I in range (1, 2): # I value from 1 to 10, step to 2
Print I
Else
print ' For loop are over '

Break and continue: for interrupts and continuation loops.

Iii. input/output of documents

Copy Code code as follows:

F=open ("Foo.txt")
Line=f.readline ()
While line:
Print line,
Line=f.readline () #读取一行, including line break ' \ n ', read to end of file, return empty string
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 and line

Four, built-in type

4.1 None Type

None represents an empty object. If a function does not show a return value, none is returned. The bool value of None is False

4.2 Numeric types

Python has 4 numeric types: integers, long integers, floating-point numbers, and complex numbers. All numeric types are immutable types.

Python does not support self-subtraction operator ++,--,++i, which is actually a + (+i) meaning

Operators and expressions: basically similar to other languages, but with the following differences:

X*y: Multiplication. 2 * 3 get 6. ' La ' * 3 gets ' Lalala '.
X**y: A power operation that returns the Y-power of X.
X/y:x divided by Y,4/3 to get 1 (integer results by division of integers). 4.0/3 or 4/3.0 get 1.3333333333333333.
X//y: Take the division of the divide. The integer portion of the return quotient. 4//3.0 gets 1.0.
Division//: floor except at any time will be a decimal part of the 0
-X Change the sign bit of x

4.3 string
String: Single quotation marks (') and double quotes (") are the same, only single line strings can be created. The escape character is (\).

Everything between the three quotes (such as: "" or "") is the content of the string.

Natural string: Adding R (or R) before a string indicates that certain strings that do not require special handling, such as the escape character, such as print R "hello\n World", will output "hello\n world" directly without a newline.

Copy Code code as follows:

A= "Hello World"
b=a[0,5] # b= "Hello"
c=a+ "I Love your" # c= "Hello World I Love You"
S= "The value of x is" + str (x)

Get substring: s[i:j], returns a substring of s from I to J (excluding J). If I omit then 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 to strings.

Unicode string: Plus U (or u) before string. As A=u ' Hello ', each character is expressed in 16 digits, "Hello" ' world ' will be automatically connected to a string "HelloWorld", "S1" U "s2" will produce U "S1S2"

strings, Unicode strings, and tuple are immutable sequences.

4.4 Lists and tuples (list & tuple)

Lists and tuples are sequences of arbitrary objects that are supported by common operations:

Copy Code code as follows:

Len ()
Append ()
Insert (Index,amember)
List[index]=anewmember

Tuple of an element: A= (a) #注意一定要个额外的逗号!
For elements in tuple, you cannot modify them, and you cannot add
The list is a mutable sequence that allows insertions, deletions, replacement elements, and so on.

Actions supported by the variable sequence:

Copy Code code as follows:

S[i]=v
S[i:j]=t # T If it's a sequence
Del S[i]
Del S[i:j]

4.5 Dictionaries

A dictionary is an associative array (or hash table), a collection of objects indexed by a keyword.

Use {} to create a dictionary

Copy Code code as follows:

a={
"username": "Loo"
"Home": "/home/loo"
"UID": 500
}
u=a["username"] #访问
a["username"]= "Lu" #修改
a["Shell"]= "/USR/BIN/TCSH" #添加
del a["Shell"] #删除
Len (a) #元素个数
a[("Loo", 123)]= "ABC"

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

Five, Cycle

Copy Code code 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]) establishes a list in which the parameters I and parameter stride are optional, by default 0 and 1 respectively.

Copy Code code 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 memory that takes up memory and takes time when a large list is needed, and to overcome this disadvantage Python provides xrange (). The xrange () function only temporarily computes the supplied value when needed, greatly saving memory.

Six, function

DEF say (message, times = 1): # The default parameter value of time is 1
Print message * times
Return time # A function that returns no value can be omitted, equivalent to returning none
Only those parameters at the end of the formal parameter list can have default parameter values, that is, you cannot declare a function parameter by declaring a formal parameter with a default value and then declaring a formal parameter that has no default value. This is because the value assigned to the formal parameter is assigned based on the position. For example, Def func (A, b=5) is valid,

But def func (a=5, b) is invalid.

Global a # Gets the globally variable a

User-defined functions:

Copy Code code 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 properties:

f.__module__ #函数所在的模块名
f.__doc__ or F.func_doc #文档字符串
f.__name__ or F.func_name #函数名
f.__dict__ or F.func_dict #支持任意函数属性的函数名字空间
F.func_code #编译后产生的字节码
F.func_defaults #包含所有默认参数的元组
F.func_globals #函数所在的模块的全局名称空间的字典
F.func_closure #None or a tuple of cells that contain bindings for the function ' s free variables.

Seven, class

Copy Code code 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

The definition of a class method:

Copy Code code 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 a subclass of C or C
Issubclass (A,B) is used to test whether a is a subclass of B

Viii. anomalies

Catch exceptions with try and except statements:

Copy Code code as follows:

Try
F=open ("file.txt", "R")
Except Ioerror,e:
Print E
Except Typeerror,e:
Print E
...
Try
Do something
Except
print ' An error occurred '

If there are ioerror anomalies, place the cause of the error in the object E, then run the except code block, and if any other type of exception occurs, the control is transferred to the except code block that handles the exception, and if the code block is not found, the program terminates, and if no exception occurs, except
The code will be ignored.

Nine, module

Import Module Name
Import Module name as Alias
From module Import object (function)
From module Import *
Built-in function dir () can list all of the accessible content in a module
Modules that can be imported by import:
1. Programs written using Python (. PY program)
2.C or C + + extensions (shared libraries or DLLs that have been compiled)
3. Package (including multiple modules)
4. Built-in modules (written using C and linked to the Python interpreter)

X. References and replicas (reference count)

All the data in Python is an object.
For a mutable object, changing a reference is tantamount to changing all references to that object:

Copy Code code as follows:

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

To avoid this, you need to create a copy of the Mutable object and then manipulate the copy.

Two copies of a mutable object are created:

(1) shallow copy (shallow copy): Creates a new object, but it contains child elements that are still references to the original object's child elements:

Copy Code code as follows:

b=[1,2,[3,4]]
a=b[:]
A.append (100)
Print B # b=[1,2,[3,4]] b no change
a[0]=100
Print B # b=[1,2,[3,4]] b no change
a[2][0]=100
Print B # b=[1,2,[100,4]] B has been changed

(2) deep copy (deep copy)

Copy Code code as follows:

Import Copy
b=[1,2,[3,4]]
A=copy.deepcopy (b)

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

Xi. Type Conversions

Copy Code code as follows:

Int (x[,base]) #转换为int
Long (X[,base])
Float (x)
Tuple (x)
List (x)
Chr (x) #转换为字符
UNICHR (x) #转换为Unicode字符
Ord (x) #字符转换为整数值
STR (x)
a=[1,2,3,4]
S=repr (a) # s= ' [1,2,3,4] ' can also use s= ' a '
B=eval (s) # b=[1,2,3,4] and convert to a list
Eval (' 3+4 ')
F=open ("foo")
A=repr (f) # a= "<open file ' foo ', Mode ' R ' at Dc030>"

12. Other

Document String Docstrings: If the first statement of a module, class, function body is an unnamed string, the change string automatically becomes the document string for that object. Something like Javadoc is plainly.

The Convention for a document string is a multiline string whose first line begins with a capital letter and ends with a period. The second line is a blank line, starting with a detailed description of the third line. You can use __DOC__ (note double underlines) to call the function's document string property (which is the name of the function). Python takes everything as an object, including this function.

Help () in Python, it does just grab the __doc__ property of the function and then show it neatly to you.

Automated tools can also extract documents from your program in the same way. Use docstrings similar to help () with the Pydoc command that comes with the Python release.

Copy Code code as follows:

def printmax (x, y):
' Prints the maximum of two numbers. ' # Here's the document string
Print "Docstrings" # This is the function Body command line argument
>>>print printmax.__doc__
Prints the maximum of two numbers.

ID (a) To view the identity of the object (the current implementation is the location of the object in memory)

Copy Code code 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 a subclass of C or C

Copy Code code as follows:

Import types
Isinstance (3,types. Inttype) #返回True

X==y compare values for x and Y are equal
X is y and x is not y compare X and Y to 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.