Find Help document Dir (method) helper (method)
For example: Dir (list) to find out the various methods of the list
The python variable is equivalent to a label, which is affixed to that big, which is where to hit
Input: A=int (Input (' Please enter an integer: '))
Output: Print (' The value of this integer is ', a)
Python does not have a function or loop of bounding brackets, only according to indentation to identify that the code is within the loop (that is, those code is the loop body),
Conditional statements are added after the if else or while statement: that is, a colon
Python variables are not defined, used directly, but more visually, a label.
Indentation is important and does not hang else, the same indentation level is the binding
For loops, unlike C, Python's for loop can automatically invoke the iterator's next method and automatically end the loop. Very smart
For-Target in expression:
Loop body
List is an array of C languages
scheduled for number=[1,2,3,4,5,5]
Len () to find the length
Range () and for loop are a pair
Range (1:5) generates 1 to 4 sequence range (5) to generate 0 to 4 sequences
List is an array of C languages
number=[1,2,3,4,5,5] List of everything can be put, the same list of different types of data can also put num=[' 123 ', 123,4] string integer object can be thrown into the list
num=[] Empty list
To add an element to a list:
Append method Num.append (' Zhang ') passed in the string ' Zhang ' but only one element at a time
Extend num.extend ([' Zhang ', ' Li ']) can be expanded as a list to add multiple
Insert (the position in the list, the inserted element)
To insert an element into the list:
Remove (the element to remove) does not need to know where the element to delete exists
Del Delete entire list
The Pop () method takes the last element out and returns the deleted element
Pop (index value) deletes the element corresponding to the index value
Get multiple list elements at once: list shards or slices
Num[1:3] Gets the index value from 1 to 2 elements to get the original list of copies, the original list does not change Num[:3] Gets the element from the first starting position (index 0) to index 2
Num[2:] Gets the index value from 2 to the last element
num[:] All elements
Other operations:
In num if 10 returns 1 in num otherwise returns 0
No in num if 10 does not return 1 in num otherwise returns 0
Num*3 copies elements from the NUM list into three batches if num=[1,2,3] num*3 is
[1,2,3,1,2,3,1,2,3] At this time the * becomes a repeating operator
Num.count (123) finds the number of occurrences of 123 elements in Num and returns
Num.index (123) returns the position of element 123 in the list (default is the first occurrence of the element)
Num.index (123,3,7) find 123 from three to 7
Num. Reverse () The entire list element is reversed in situ
Num.sort () Sort by default small to large sort num.sort (reverse=true) from large to small arrangement
Print (' This is%.4f '%2.12345)
This is 2.1235 format output
Yongzu elements cannot be changed after they are defined, they cannot be deleted and inserted, but the meta-ancestor can be updated this is not the same as the list.
Ganso with parentheses when creating
tuple1= (1,2,3,,4,5,6,7,8) Ganso Tuple1 methods and lists for accessing elements
The definition of the Ganso of an element tuple1= (1,) or tuple=1, must have a comma or the integer type.
Tupl1=1,
Tuple2= (' Zhang ', ' Li ', ' Wang ') updated the Yuan Zu
How to insert an element in Yongzu
tuple1= (' Li Ning ', ' Adidas ', ' Nike ', ' Anta ')
Join 361
tuple1=tuple1[:2]+ (' 361 ',) +tuple2[2:] Stitching
Synthetic Li ning Adidas 361 Nike Anta
String: str
Str= ' I love my school '
STR[2] Find the element with index 2, which is L
Python does not have the concept of a character
str=str[:2]+ (' 361 ',) +str[2:] Some basic operation strings of the concatenation list can also be used with slices, comparison operators, and the logical operator member operator in is not the same as the list
String formatting: The Format function receives positional parameters and keyword arguments
Unknown parameter ' {0} ' love {1}. {2} '. Format (' I ', ' I ', ' now ') curly braces are required to represent substitution fields
' I love You.now '
Keyword parameter ' {a} love {b}. {c} '. Format (a= ' i ', b= ' you ', c= ' now ')
As a result
' {{0} '. Format (' You're awesome ') output ' {0} ' does not output you really good, because 0 has been included in curly braces, lost the meaning of the previous
Formatting:
' {0:.2f}{1} '. Format (2.345, ' result ') where the {0:.2f} colon represents the beginning of the format followed by the formatting operator. Point 2 means keep two decimal places F is floating point number
Formatted strings are the same as printf C language Features
'%c '% 97 played ' a '
Print ('%c '%97)
Formatted integer: Print ('%d '%9.7) output 9
List meta-progenitor strings are indexed and are indexed from 0 can be shards can have some basic operators
Sequence: A generic term for a list of meta-progenitor strings
Common built-in methods for sequences:
List () converts an object into a list object
B= ' I love my school '
B=list (b)
b=[' i ', ' ', ' l ', ' o ', ' V ', ' e ', ' ', ' m ', ' y ', ', ' s ', ' C ', ' H ', ' o ', ' o ', ' l ']
Tuple () Converts an iterative object into a Ganso
Len (a) returns the length of a
Max (a) returns the parameter a (the maximum value of the sequence or the progenitor)
Min (a) returns the parameter a (the minimum value of the sequence or progenitor)
Sum (a) returns and the above four require elements to be unified in order to
Sorted () sort
Reversed () Reverses its result not the inverted ganso but one = an iterator we use:
A Tuple (reversed ()) or list (reversed ()) returns the inverted element
Well
List (Enumerate (a)) enumeration type A is a list enumerate (a) returns an iterator that needs to be added to list to display
[(0, 1), (1, 2), (2, 1), (3, 3), (4, 4), (5, 12)]
Dictionary:
The dictionary defines the dictionary not as a sequence type, but as a mapping type and cannot be accessed with an index.
dir1={' Li Ning ': ' Everything is possible ', ' Nike ': ' Imposible is nothing ', ' anta ': ' Never Stop ',}
Li Ning is key everything can be value values they are separated by a colon
Index:
Print (' Anta slogan is: ', dir1[' Anta ')
Anta's slogan is: Never stop
Example: dir2={1: ' Zhang ', 2: ' Rui ', 3: ' Lin '}
>>> Dir2
{1: ' Zhang ', 2: ' Rui ', 3: ' Lin '}
Create dictionary: dirct1={};
Using the Dict function dict is only one parameter
Dirt3=dict ((1, ' Zhang '), (2, ' Rui '), (3, ' Lin ')) so to disguise the three progenitor as a meta-ancestor that is three parentheses (carefully understood)
>>> Dirt3
{1: ' Zhang ', 2: ' Rui ', 3: ' Lin '}
Modify the dictionary element originally: {1: ' Zhang ', 2: ' Rui ', 3: ' Lin '}
dirt3[1]= ' Dashibi '
>>> Dirt3
{1: ' Dashibi ', 2: ' Rui ', 3: ' Lin '} even if there is no such index in the dictionary, one is added automatically.
Fromkeys Create a new key value and return Note: Only definitions cannot be used to modify elements in the dictionary
Dict5=dict5.fromkeys ((), (' One ', ' one ', ' one ', ' three ')
Output:
{1: (' One ', ' one ', ' ' Three '), 2: (' One ', ' one ', ' three '), 3: (' One ', ' one ', ' three ')}
Dict5=dict5.fromkeys (1, (' One ', ' Zhang ') thought that modifying the first element in the dictionary was actually not,
The output dict5 is 1:zhang and becomes a new dictionary.
E=dict5.fromkeys (Range (12), ' Diao ')
>>> E
{0: ' Diao ', 1: ' Diao ', 2: ' Diao ', 3: ' Diao ', 4: ' Diao ', 5: ' Diao ', 6: ' Diao ', 7: ' Diao ', 8: ' Diao ', 9: ' Diao ', 10: ' Diao ', 11: ' Diao '}
Keys () Usage
>>> for I in E.keys ():
Print (i)
0
1
2
3
4
5
6
7
8
9
10
11
>>>
VALUES () Usage
>>> for I in E.values ():
Print (i)
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
Mouth
>>>
Get element
Get () method
Check whether the index value has
For example, check the key value 32
Direct-in E has a return true no return false
In is not a membership operator
Empty dictionary
Clear ()
Pop () The given key pops a value
Popitem () pops up an item
SetDefault (5, ' Baba ') joins a key value of 5 with a value of Baba
Update () updates the dictionary with a mapping relationship
Dirt3={1: ' Zhang ', 2: ' Rui ', 3: ' Lin '}
>>> Dirt3
{1: ' Zhang ', 2: ' Rui ', 3: ' Lin '}
>>> Dirt3.pop (1)
' Zhang '
>>> Dirt3
{2: ' Rui ', 3: ' Lin '}
>>> Dirt3
{2: ' Rui ', 3: ' Lin '}
>>> Dirt3.setdefault (6, ' Baba ')
' Baba '
>>> Dirt3
{2: ' Rui ', 3: ' Lin ', 6: ' Baba '}
>>> b={' Little white ': ' Gou '}
>>> Dirt3.update (b)
>>> Dirt3
{2: ' Rui ', 3: ' Lin ', ' Little white ': ' Gou ', 6: ' Baba '}
Collection:
And the dictionary is cousin
>>> jihe={12,3,4} also use curly braces
>>> type (JIHE)
<class ' Set ' > It's a set that's like a dictionary definition.
The element of the collection is the only duplicate element that will be automatically rejected
The collection is unordered and cannot be indexed
Create collection: jihe={1,2,3,,4}
Set () factory function
Jihe=set ([1,2,3,4]) The parameter of the set () function is now a list, or it can be a ganso or a string
>>> Jihe
{1, 2, 3, 4}
You can use a for loop to read every element
Can be used to determine whether an element is in the collection
Add (1) add element 1
Remove (1) Remove element 1
File operations
F=open (' e:\\recovery.txt ', ' RT ') Open the E-disk under the recovery file read-only mode F for the file object
F.read () Read all
' Rui UI Anhui people room card charge way to tell \ Haverdahl start a holiday achilles \ \ Love the plane Dragonair master fell in love with coffee \nafsjkfnalkf, \ n Love began to send greeting cards called Master good \ n '
The read pointer at this point points to the last
>>> f=open (' e:\\recovery.txt ', ' RT ')
>>> F.read (4) read five character (s)
' Rui UI '
>>> F.tell () read out where the pointer is
7
Python is flexible.
Can convert a file object into a list
>>> f=open (' e:\\recovery.txt ', ' RT ')
>>> list (f)
[' Rui UI Anhui people room card charge way to tell \ n ', ' Haverdahl began to holiday Achilles \ \ ', ' fell in love with the plane Dragonair master love coffee \ n ', ' afsjkfnalkf, \ n ', ' love began to send greeting cards called Master Good '] that content is included in the
Every line is read out.
>>> f=open (' e:\\recovery.txt ', ' RT ')
>>> a=list (f)
>>> for I in a:
Print (i)
Rui UI Anhui people room card charge way tell
Haverdahl started a holiday, Achilles.
Fell in love with the plane Dragonair master was in love with coffee
AFSJKFNALKF,
Love begins to send a greeting card called Master good
Write file:
>>> file=open (' E:\\test.txt ', ' W ')
>>> file.write (' Zhangruilin ') write Zhangruilin
11
>>> File.seek (0,0) pointer zeroing
0
>>> for i in file: output
Print (i)
Module:
Some operations on files in the OS module
Import OS Importing module
OS.GETCWD ()
Os.listdir (' e:\\ ')
Os.mkdir (' c:\\b ')
>>> os.remove (' d:\\ from. jpg ')
>>> os.rmdir (' c:\\b ')
Os.path modules are useful
Pickle Module
Can be used to save files, saved as various types of files, not limited to text files
Convert complex data types, such as list dictionaries, into binary files.
>>> m_list=[123,3.14, ' Zhangruilin ', [' answer ']
>>> pickl_file=open (' my_list.pkl ', ' WB ') suffix does not matter the content is not changed WB read-only binary save step
>>> pickle.dump (m_list,pickl_file) Save file
>>> Pickl_file.close ()
>>> pickl_file=open (' my_list.pkl ', ' RB ')
>>> my_list=pickle.load (Pickl_file) reply to the entire list read out step
>>> my_list
[123, 3.14, ' Zhangruilin ', [' answer ']
Example: Save some unnecessary files through the Pickle module
>>> m_list1=[' 123 ', ' 234 ']
>>> pickle1=open (' c:\\zhangruilin.pkl ', ' WB ')
>>> pickle1=open (' c:\\zhangruilin.pkl ', ' WB ')
>>> Pickle.dump (M_list1,pickle1)
>>> Pickle1.close ()
>>> pickle1=open (' c:\\zhangruilin.pkl ', ' RB ')
>>> A=pickle.load (Pickle1)
>>> A
[' 123 ', ' 234 ']
Abnormal:
Try:
F=open (' C:\\ac.txt ', ' W ')
Print (F.write (' I exist '))
sum=1+ ' 1 '
F.close ()
Except (Oserror,typeerror):
Print (' ERROR ')
Finally
F.close ()
Rich Else statement else can match while and try
Executes the next else statement when it is not executed in the while
The Else statement is executed when there is no error in the try
Try:
F=open (' C:\\ac.txt ', ' W ')
Print (F.write (' I exist '))
sum=1+ ' 1 '
F.close ()
Except (Oserror,typeerror):
Print (' ERROR ')
Else:
Print (' zhangrui;in ') when there is no error in the try, it executes the
A=1
While a!=2:
Print (' Nishishiba ')
a++
Else: Executes the else statement when the while does not execute
Print (' Sadiyage ')
The WITH statement abstracts out some common actions of the file, helping us to automatically close the file
Try:
With open (' C:\\ac.txt ', ' W ') as F:with will pay attention to when this file is not used he will automatically call off
Print (F.write (' I exist '))
sum=1+ ' 1 '
Except (Oserror,typeerror):
Print (' ERROR ')
Start of class capital letters in Puthon, start of function lowercase letter
Python is an object-oriented inheritance package polymorphism has
Inherited
Class A (list): Parameter list means that Class A inherits the list class
Pass represents this class and does nothing just to demonstrate
>>> B=a ()
>>> B.append (34) object B inherits all functions of the list class
>>> b
[34]
Python's self and C + + 's This pointer is the identity symbol (identifying an object) of each class's object
The definition takes care to write self into the first argument when the class is defined.
Class Gun:
def fun (self,name):
Self.name=name
def shoot (self):
Print (' The Weapon function is%s '%self.name)
>>> A=gun ()
>>> A.fun (' Machine gun ')
>>> B=gun ()
>>> B.fun (' Automatic rifle ')
>>> A.shoot ()
The weapon function is machine gun
>>> B.shoot ()
The weapon function is an automatic rifle
Magic Method:
_init_ (SELF,CANSHU1,CANSHU2) function is C + + constructor Note double underline
Class Gun:
def __init__ (self,name):
Self.name=name automatically called when an object is established
def shoot (self):
Print (' The Weapon function is%s '%self.name)
>>> B=gun (' Heavy machine gun ') call without tube first parameter
>>> B.shoot ()
The weapon function is heavy machine gun
Private variables in Python define private variables with two underscores in front of the variable name or function name
Super. Plus the method of the required parent class () Super can help us invoke the method defined by the parent class
For example:
Import Random as R
Class Fish:
def __init__ (self):
Self.x=r.randint (0,10)
Self.y=r.randint (0,10)
def move (self):
Self.x-=1
Print (' My location is: ', SELF.X,SELF.Y)
Class Goldfish (fish):
Pass
Class Salman (fish):
Pass
Class Carp (fish):
Pass
Class shark (fish):
def __init__ (self):
Super (). __init__ () No name given to any base class
Self.hungry=true
Def eat (self):
If Self.hungry:
Print (' The dream of a foodie is to eat every day ')
Self.hungry=false
Else
Print (' Fed up, can't eat ')
>>> Shark=shark ()
>>> Shark.move ()
My position is: 9 1
Python Basic Grammar Compilation Summary