Python Basics Primer (file input/output built-in type dictionary operation using method)

Source: Internet
Author: User
Tags case statement integer division natural string shallow copy uppercase letter
I. Variables and Expressions

Copy the 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 the appropriate type based on context auto-resolution. Python is a dynamic language in which the same variable name can represent different forms of values (integer, float, list, tuple) during the run of the program, and the variable name is simply a reference to various data and objects. The variable name in the C language is the memory fragment used to hold the result.

1. In Python, it is assigned to a variable by reference to the object instead of by value.

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

3, in the C language, the assignment statement can be used as an expression (can return a value), but in Python the assignment statement does not return a value, as the following is illegal:
Copy the Code code as follows:


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

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

The line that begins with # is called a comment.

Second, conditional statements

Control flow statements: Arbitrary conditional expressions can be established by using the Or,and,not keyword

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

Copy the Code code as follows:


if something = = 1:
DoSomething1 ()
elif something = = 2:
DoSomething2 ()
Else
Pass # denotes 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 is 2
Print I
Else
print ' The For loop was over '

Break and continue: used for interrupts and continuation loops.

Iii. input/output of the file

Copy the Code code as follows:


F=open ("Foo.txt")
Line=f.readline ()
While line:
Print line,
Line=f.readline () #读取一行, including line feed ' \ 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 with line

Iv. built-in type

4.1 None Type

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

4.2 Numeric types

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

Python does not support the self-increment decrement operator ++,--,++i, which is actually the meaning of + (+i)

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

X*y: Multiplication. 2 * 3 gets 6. ' La ' * 3 get ' 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 division to get an integer result). 4.0/3 or 4/3.0 get 1.3333333333333333.
x//y: Divide evenly. Returns the integer portion of the quotient. 4//3.0 gets 1.0.
Division//: The floor will be 0 of the fractional part at any time.
-X Change the sign bit of X.

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

Everything between three quotation marks (such as "' or" ") is the contents of a string.

Natural string: A string preceded by R (or R) indicates certain strings that do not require special handling, such as the escape character, such as: Print R "hello\n World", which will output "hello\n world" without any newline.

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


Get substring: s[i:j], returns the substring between s from I to J (not including J). If I omit then i=0, if J is omitted then J=len (s)-1

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

Unicode string: Add U (or U) before the string. such as A=u ' Hello ', each character with 16 bits to indicate "Hello" ' world ' will be automatically connected to a string "HelloWorld", "S1" U "s2" will produce U "S1S2"

strings, Unicode strings, and tuples are immutable sequences.

4.4 Lists and tuples (list & tuple)

Lists and tuples are sequences of arbitrary objects that support common operations:
Copy the Code code as follows:


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

Tuple of an element: A= (#注意一定要个额外的逗号)!
For elements in a tuple, it is not possible to modify or add
Lists are mutable sequences that allow operations such as inserting, deleting, replacing elements, etc.

Operations supported by variable sequences:
Copy the 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), which is a collection of objects indexed by a keyword.

Use {} to create a dictionary

Copy the 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"

A dictionary key is an object (such as a number and a tuple) that cannot be modified.

V. Circulation

Copy the 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, parameter I and parameter stride are optional, and defaults to 0 and 1, respectively.

Copy the 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, which takes up memory and time when a large list is needed, and in order to overcome this disadvantage, Python provides xrange (). The xrange () function only temporarily calculates the value provided when needed, saving memory significantly.

Vi. functions

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

However, the Def func (a=5, b) is invalid.

Global a # Gets the globals variable a

User-defined functions:

Copy the 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.

Vii.. Class

Copy the 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

Definition of a class method:

Copy the 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 if s is an instance of a subclass of C or C
Issubclass (A, b) is used to test whether a is a sub-class

Eight, abnormal

Use the try and except statements to catch exceptions:

Copy the 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 is an IOError exception, place the error cause in Object E, then run the except code block, and if another type of exception occurs, take control to the code block of the except that handles the exception, if the code block is not found, the program terminates, and if no exception occurs, the except generation
Code will be ignored.

Nine, 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 using Python (. PY program)
2.C or C + + extensions (compiled shared libraries or DLLs)
3. Package (contains multiple modules)
4. Built-in modules (written in C and linked to the Python interpreter)

X. References and replicas (reference counting)

All data in Python is an object.
For mutable objects, changing a reference is tantamount to altering all references to that object:
Copy the Code code as follows:


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


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

Two copies of creating mutable objects:

(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 the Code code as follows:


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

(2) deep copy

Copy the 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 Conversion

Copy the 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= " "

12. Other

Document String Docstrings: If the first statement of a module, class, or function body is an unnamed string, changing the string automatically becomes the document string for that object. Plainly, it is something like Javadoc.

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

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

Automation tools can also extract documents from your program in the same way. Similar to help (), use docstrings with the Pydoc command that came with the Python release.

Copy the Code code as follows:


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


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

Copy the 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 if s is an instance of a subclass of C or C

Copy the 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 the same object in memory
  • 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.