1. Some basic rules and special characters in Python statements
2. Variables
The variable does not need to be declared in advance. Once assigned, the variable can be used. The variable does not need to specify a type. The object type and memory usage are determined at runtime, And the variables are dynamic, you do not need to specify the variable type. Var = 1Print var
Var = "hello"Print var
Note: programmers do not need to care about memory management. The Python interpreter undertakes complex tasks of memory management and variable names are recycled. The del statement can directly release resources.
3. Import Module
Import sysSys. stdout. write ('Hello world! \ N ')Print sys. platformPrint sys. version
Import PersonClassS = PersonClass. Student ("zhangzhe", 25, 60, 2)S. speak ()
Import PersonClass as TestS = Test. Student ("zhanghze", 23,32, 2)S. speak ()
From PersonClass import StudentS = Student ("zhangzhe", 25, 60, 2)S. speak ()
4. New built-in functions of Pyhon
Ls1 = range (2, 10, 2)
Print ls1 # [2, 4, 6, 8]
5. Notes# This is a comment# You can also add a string at the beginning of a module, class, or function to serve as an online document. This is a feature familiar to Java programmers.
Def foo ():"This is a doc string ."Print "foo funtion called ."Return True
6. Number
7. String First, the difference between double quotation marks (1) and three double quotation marks (3). Strings represented by double quotation marks are usually written as one line.For example:S1 = "hello, world"If you want to write multiple lines, you need to use the \ ("hyphen"), for example:S2 = "hello ,\World"S2 is the same as s1. If you use three double quotes, you can write them directly, as shown below:S3 = "" hello,World,Hahaha. "", s3 is actually "hello, \ nworld, \ nhahaha.", note "\ n ",So,If you have many \ n strings and you do not want to use \ n in the strings, you can use three pairs.Quotation marks. You can also add comments to the string using three double quotes, as shown below:S3 = "hello, # hoho, this is hello, which can be annotated in a string of three double quotes.World, # hoho, this is worldHahaha ."""
This is the difference between three double quotes and one double quotation mark. The difference between the three double quotes and one single quotation mark is alsoIt is the same as this. In fact, there is a reason why python supports single quotation marks. Here I will compare the difference between one single quotation mark and one double quotation mark. When I use single quotes to represent a string, if you want to represent the string Let's go, it must be like this: s4 = 'let \'s go '. Note that no, there is a 'in the string, and the character string is expressed with'. Therefore, you must use the Escape Character \ (\, you should know the escape character ), if your string contains a lot of escape characters, it looks uncomfortable. python also solves this problem well, as shown below: s5 = "Let's go, python knows that you use "to represent a string, so python treats the single quotation mark in the string as a normal character, isn't it easy. The same applies to double quotation marks. The following is an example of s6 = 'I realy like "python "! '
8. Operators
Arithmetic Operators +,-, *,/, //, %, and **/perform floor Division: If two operands are integer, he will explain how to perform floor division if two (take the largest integer smaller than the quotient) // floating point Division: No matter what type of the operand is, the floating point Division always executes the real division. ** Multiplication Operator
Comparison operator
Logical operators
9. tuples and lists
The list uses [] to indicate that tuples use () to indicate that tuples can be viewed as read-only lists.
10. Dictionary The dictionary is the ing data in Python. Represented {}Key: It can be any type of object in Python, generally numbers and strings.Value: It can be any type of Python object.
M = {'A': 1, 'B': 2, 'C': 3}
Print (m)Print (m ['a'])Print (m. get ('B '))
M2 = m. copy ()Print (m2)M2 ['a] = 100Print (m2)Print (m)
Print (m. keys ())Print (m. values ())Print (m. items ())
M. pop ('A ')Print (m)
11. code block and indent alignment
The code block uses indentation to align the expression logic, rather than braces. Because there are no additional characters, the program is more readable.
12. if statement
X =-2
If x <. 0: # if the expression value is non-zero or the Boolean value is True, run if_suit (code group)
Print "x <0"Elif x = 0:Print "x = 0"Else:Print "x> 0"
13. for Loop and range () built-in functions
For item in ['hello', 'World', 'China']:
Print item, # Can be output in the same row with a comma X = 'helo world'For c in x:Print c,
X = 'foo'For I in range (len (x )):Print x [I], '(% d)' % I
For index, ch in enumerate (x ):Print ch, '(% d)' % (index)
14. List ParsingYou can use the for Loop in a row to put all values in a list.Square = [x * 2 for x in range (4)]Print square
Square = [x ** 2 for x in range (4)]Print square
Square = [x * 2 for x in range (4) if x % 2 = 0]Print square
15. file and built-in functions open () and file () Import pickleImport struct
D = {'A': 1, 'B': 2}F = open('datafile.txt ', 'wb ')Pickle. dump (d, f)F. close ()
F = open('datafile.txt ', 'rb ')E = pickle. load (f)Print e
F = open ('data. bin', 'wb ')
Data = struct. pack ('hhl ', 1, 2, 3)F. write (data)F. close ()
F = open ('data. bin', 'rb ')Data = f. read ()Values = struct. unpack ('hhl ', data)Print values
16. Errors and exceptions
Try: list [2]/0 then t IndexError: print ("indexError") failed t ZeroDivisionError: print ("zeroDivisionError") else: print "no error" finally: print ("finally ")
# Define custom exceptionclass LengthRequiredException (Exception): def _ init _ (self, length, minLength): Exception. _ init _ (self) self. length = length self. minLength = minLength
L = [1, 2, 3, 4, 5, 6] minLength = 6
Try: raise LengthRequiredException (len (l), minLength) failed t IndexError: print ("index out of bounds") failed t LengthRequiredException: print ("Length not fit: length is % d required % d ") else: print (" no exception was raised. ") finally:Print ("finally will be execute ")
Class Test (object): def _ enter _ (self): print ("enter...") return 1
Def _ exit _ (self, exc_type, exc_val, exc_tb): print ("exit...") return True
With Test () as t: print ("t is not the result of test (), it is _ enter _ returned") print ("t is 1, yes, it is {0 }". format (t) raise NameError ("Hi there ")Print ("Never here ")
17. Functions
Def AddMe2Me (x = 20 ):Return (x + x)
Print AddMe2Me ()X = 10Print AddMe2Me (x)Print AddMe2Me ('python ')AddMe2Me ([1, 'abc'])
18. Class Class private attribute :__ private_attrs starts with two underscores. This attribute is declared as private and cannot be used outside the class or accessed directly. self is used in internal class methods. _ private_attrs
Class method. Within the class, you can use the def keyword to define a method for the class. Unlike the general function definition, the class method must contain the self parameter and be the first parameter.
The private class method, __private_method, starts with two underscores and declares that this method is a private method. It cannot be called outside the class, and slef. _ private_methods can be called inside the class.
Class proprietary method:
_ Init _ constructor. when an object is generated, the _ del _ destructor is called. When the object is released, the _ repr _ print is used, convert _ setitem _ assign value by index _ getitem _ obtain value by index
_ Len _ Get length _ cmp _ comparison calculation _ call _ function call _ add Calculation _ sub _ subtraction calculation _ mul __ multiplication calculation _ div _ Division calculation _ mod _ remainder calculation _ pow _
Class People:
"People class doc ."
# Attribute
Name =''
Age = 0
_ Weight = 0
# Method
Def _ init _ (self, aName, aAge, aWeight ):
Self. name = aName
Self. age = aAge
Self. _ weight = aWeight
Def speak (self ):
Print ("% s is speaking: I am % d years old." % (self. name, self. age ))
Unique inheritance
Class Student (People ):
# Attribute
Grade = 10
# Method
Def _ init _ (self, aName, aAge, aWeight, aGrade ):
People. _ init _ (self, aName, aAge, aWeight)
Self. grade = aGrade
Def speak (self ):
Print ("% s is speaking: I am % d years old. I am in grade % d." % (self. name, self. age, self. grade ))
Multi-inheritance: Pay attention to the sequence of the parent class in parentheses. If the parent class has the same method name but is not specified in the subclass, search for python from left to right, that is, if the method is not found in the subclass, you can check from left to right whether the parent class contains the method.
Class Speaker ():
Topic =''
Name =''
Def _ init _ (self, aTopic, aName ):
Self. name = aName
Self. topic = aTopic
Def speak (self ):
Print ("I m % s, I am a speaker! My topic is % s. "% (self. name, self. topic ))
Class Sample (Speaker, Student ):
A =''
Def _ init _ (self, aTopic, aName, aAge, aWeight, aGrade ):
Speaker. _ init _ (self, aTopic, aName)
Student. _ init _ (self, aName, aAge, aWeight, aGrade)