Catalog
data type
Number
Integers
Floating point numbers
character string
String splicing
String processing (8 Common use )
' It is also a character
Escape character
Boolean value
Boolean values can be used and、or and not operation .
Add
Null value
matters needing attention
List( list )
List functions
Tuple( Tuples )
dict(dictionary)
Dictionary function
dict What can't be found
set( aggregate )
Set function
function
Defined function
Parameter check
Return multiple values
Call function
The parameters of the function
Positional arguments
Default parameters
Variable parameters
Recursive function
IO File read and write
Read the file
Writing documents
Loop statement
for loop
for A nested loop
while loop
while A nested loop
iterator
exception handling
Capture exception try...except...
Catch multiple exceptions
Immutable data types :Number、String、Tuple
Variable data :List、Dictionary、Setumber
Number It can be divided into :int( Integers )、float( Floating point numbers are decimals )、String( character string )、bool( Boolean value )
Python Can handle integers of any size , Including, of course, negative integers , The expression method is consistent with the mathematical writing .
Allow... In the middle of numbers _ Separate
10_000_000_000 and 10000000000
Floating point numbers are decimals , It's called floating point number , Because according to the scientific notation , The decimal position of a floating point number is variable . Floating point numbers can be written mathematically , Such as 1.23,-9.01 wait .
stay Python in In scientific counting method 10 use e replace .
Strings are in single quotes ' Or double quotes " Any text enclosed .
Put together a comma , Then a space will appear in the comma .
Use the plus sign to splice , There are no spaces . If you want spaces , Then a space should be added
print("Hello","World") # Output :Hello World
print("Hello"+"World") # Output :HelloWorld
print("Hello"+" "+"World") # Output :Hello World
len(): Returns the length of the string , That is, the number of single elements in the string
length=len(target_string) #target-string Is the target string variable
upper(): Convert all characters in the string to uppercase
lower(): Convert all characters to lowercase
title(): Change the first letter of all words in the string to uppercase , The other letters are still lowercase
new_string="Tom is good"
print(name_string.upper()) # Output :TOM IS GOOD
print(name_string.lower()) # Output :tom is good
print(name_string.title()) # Output :Tom Is Good
strip(): You can remove both sides of the string ( Does not include internal ) All spaces . Using this method , You can also specify parameters , Remove specific characters specified on both sides
split(): Implement string splitting . This method is based on the provided delimiter , Split a string into a list of characters , If no delimiter is provided , The program will default to the space ( Tabulation 、 Line break, etc ) As a separator .
find(): Using this method, you can find substrings in a long string . If in this string , There are one or more substrings , The method returns the leftmost index of the first substring , If no qualified substring is found , Then return to -1.
replace(): To replace substrings in a given string .
source_string.replace(old_string, new_string)
use "" Cover up
Escape character \ Can escape many characters , such as \n Means line break ,\t Represents a tab , character \ We need to escape ourselves , therefore \\ The character is \ .
When the string contains both ' Contain, ", Use escape characters
special case :
use r'' Express '' The internal string does not escape by default
use '''...''' The format of represents multiline content
stay Python in , It can be used directly True、False Represents a Boolean value ( Please pay attention to the case )
and Operation is with operation , Only for True,and The result is True
or Operation is or is , As long as one of them is True,or The result is True
not Operation is not operation , It's a monocular operator , hold True become False,False become True
None It can't be understood as 0, because 0 It makes sense , and None Is a special null value .
Python The grammar of : Indent mode ( There is no rule whether the indentation is a few spaces or Tab, The Convention is 4 Indent of spaces )
Python Case sensitive .
List It's an orderly collection , Can appear as a comma separated value in square brackets .List The data types of the elements inside can also be different , You can add and remove elements at any time .List The element can also be another List( But the other List Only one element , It can be understood as a two-dimensional array ).
List None of the elements in , It's just an empty list, Its length is 0
Format :List=['a','b','c']
len(list) # get list Number of elements
list.append(obj) # Add a new object at the end of the list
list.count(obj) # Count the number of times an element appears in a list
list.extend(seq) # Appends multiple values from another sequence at once at the end of the list ( Extend the original list with the new list )
list.index(obj) # Find the index position of the first match of a value in the list
list.pop() # Removes an element from the list ( Default last element ), And returns the value of that element
list.remove() # Removes the first match of a value in the list
list.reverse() # Reverse list of elements
list.sort(key=None,reverse=False) # Sort the original list ,True Descending ,False Ascending ( Default )
list.clear() # clear list
list.copy() # Copy list
tuple And list Very similar , But once initialized, it cannot be modified .
Other ways to get elements and list It's the same , But it can't be assigned to another element .
Only 1 An element of tuple A comma must be added to the definition ,Python In the display, only 1 An element of tuple when , A comma will also be added ,, In case you misunderstand it as a bracket in the sense of mathematical calculation .
tuple So-called “ unchanged ” Is said ,tuple Each element of , Direction never changes .
Python Built in dictionary :dict Support for ,dict Full name dictionary, Also known in other languages as map, Use the key - value (key-value) Storage , With extremely fast search speed .
d = {key1 : value1, key2 : value2 }
principle : First in the index table of the dictionary ( For example, the radical list ) Look up the page number of this word , Then go straight to the page , Find the word .
Be careful :dict The order of internal storage and key It doesn't matter in what order
radiansdict.clear() # Delete all elements in the dictionary
pop(key[,default]) # Delete dictionary given key key The corresponding value ,
# Return the deleted value .key Value must be given . otherwise , return default value
When you can't find it, an error will be reported , So there are two ways to avoid reporting errors .
One is to pass. in Judge key Whether there is :'' in list
Two is through dict Provided get() Method , If key non-existent , Can return None, Or as you specify value
A set is an unordered sequence of distinct elements , You can use braces { } perhaps set() Function to create a collection
set and dict similar , It's also a group. key Set , But no storage. value. because key Can't repeat , therefore , stay set in , No repeat key.
Be careful : To create an empty set, you must use set() instead of { }, because { } Is used to create an empty dictionary
Repeating elements in set Automatically filtered
s.add() # Add an element to the collection
s.clear() # Remove all elements from the collection
s.copy() # Copy a collection
s.remove() # Remove elements
Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .
Function can improve the modularity of application , And code reuse .
Format :
def Function name ():
Code
Empty function
If you want to define an empty function that does nothing , It can be used pass sentence (pass Can be used as a placeholder ):
def nop():
pass
When you call a function , If the number of parameters is wrong ,Python The interpreter will automatically check out , And throw TypeError. But if the parameter type is wrong ,Python The interpreter can't help us check .
The return value is one tuple! however , In grammar , Return to one tuple Brackets can be omitted , Multiple variables can receive one at the same time tuple, Assign corresponding value by position , therefore ,Python The function of returns multiple values is actually to return a tuple, But it's easier to write .
Format :
Function name ()
Every time a function is called , Functions are executed from scratch , When the code in this function is executed , It means that the call is over . Of course, if the function executes return It will also end the function .
example :power(x) #x This is the position parameter
When there are more than two parameters in brackets , Arguments should be placed in the order of formal parameters , Pass in .
The default parameter can simplify the function call . The biggest advantage is that it can reduce the difficulty of calling functions .
def enroll(name,city='Beijing'):
print('name:',name)
print('city:',city)
enroll('Jim')
Be careful :
First, the required parameters are in front of , The default parameter is after , otherwise Python The interpreter of will report an error ( Think about why the default parameter cannot be placed before the required parameter );
The second is how to set the default parameters .
When a function has more than one parameter , Put the variable parameters ahead , Change small parameters behind . The parameter with small change can be used as the default parameter .
stay Python Function , Variable parameters can also be defined . seeing the name of a thing one thinks of its function , Variable parameter is that the number of parameters passed in is variable , It can be 1 individual 、2 From one to any one , It can also be 0 individual .
To define this function , We have to determine the input parameters . Because the number of parameters is uncertain , We first thought that we could a,b,c…… As a list or tuple Come in . But when it's called , You need to assemble one first list or tuple.
Define variable parameters and define a list or tuple Parameter comparison , Just add one before the parameter * Number . Inside the function , Parameters numbers What was received was a tuple, therefore , The function code is completely unchanged . however , When the function is called , You can pass in any parameter , Include 0 Parameters .
*nums Express the nums This list All elements of are passed in as variable parameters .
Inside the function , You can call other functions . If a function calls itself internally , This function is a recursive function .
The advantage of recursive functions is that they are easy to define , Clear logic . Theoretically , All recursive functions can be written in a circular way , But the logic of the loop is not as clear as recursion .
Use recursive functions to prevent stack overflow . The solution to the overflow of recursive call stack is to optimize by tail recursion , In fact, tail recursion has the same effect as loop , therefore , It is also possible to treat a loop as a special tail recursive function .
Tail recursion means , When the function returns , Call itself , also ,return Statement cannot contain expression . such , Compiler or interpreter can optimize tail recursion , Let recursion itself be called no matter how many times , It only takes up one stack frame , There will be no stack overflow .
The function of reading and writing files on disk is provided by the operating system , The modern operating system does not allow ordinary programs to operate the disk directly , therefore , To read and write a file is to ask the operating system to open a file object ( Usually called a file descriptor ), then , Read data from this file object through the interface provided by the operating system ( Reading documents ), Or write the data to the file object ( Writing documents ).
Use Python Built in open() function , Pass in the filename and identifier , identifier 'r' Express reading .
f=open('F:\eclipse\eclipse\sy9T3.txt','r')
If the file does not exist, it will throw FileNotFoundError.
After successfully opening the file , call read() Methods read all the contents of the document at one time .
f.read();
Last call close() Method to close the file. The file must be closed after use , Because file objects take up operating system resources , And the operating system can open a limited number of files at the same time .
f.close()
In order to avoid too much content , Call again and again read(size) Method , Read at most each time size Bytes of content .
among readline() You can read one line at a time , call readlines() Read everything at once and return... By line list.
IOError exception handling
Because it is possible to produce IOError, Once the error , hinder f.close() Will not call . therefore , In order to ensure that the file can be closed correctly whether there is an error or not , We handle exceptions in advance :
Method 1 :
try...finally
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
Method 2 :
introduce with
with open('/path/to/file', 'r') as f:
print(f.read())
The second method is more concise , And you don't have to call f.close() Method .
UnicodeDecodeError exception handling
read() May throw UnicodeDecodeError(encoding No matter how it is used utf8、gb2312、gbk The coding method is not good )
terms of settlement :
Read in binary mode instead :open('xxx.xsl','rb')
f=open('F:\eclipse\eclipse\sy9T3.txt','rb')
f.read()
Writing a file is the same as reading a file , The only difference is to call open() Function time , Passed in identifier 'w' perhaps 'wb' To write a text file or binary file :
f=open('F:\eclipse\eclipse\sy.txt','w')
f.write("I love Python!")
f.close()
After the above operations , Click open file
notes :1. Only a call close() When the method is used , Only the operating system can ensure that all the data not written is written to the disk .
2. With 'w' When mode writes to a file , If the file already exists , Will directly cover ( Equivalent to deleting and writing a new file ).
You can pass in 'a' To add (append) Mode writing Append to end of file
f=open('F:\eclipse\eclipse\sy.txt','a')
f.write("end")
f.close()
for x in ... A loop is to substitute each element into a variable x, Then execute the indented block statement .
for each in range(3):
print(each)
0
1
2
Python Provide a range() function , You can generate a sequence of integers , Re pass list() Function can be converted to list
list=['eat','sleep','study']
for act in list:
print(" is ",act)
is eat
is sleep
is study
range(101) You can generate 0-100 Integer sequence of
for iteration_var in sequence:
for iteration_var in sequence:
Loop statement
As long as the conditions are met , It's going to keep cycling , Exit the loop if the condition is not met .
while i<3: # Judge the condition
print(i) # Loop statement
i=i+1
0
1
2
In circulation ,break Statement can exit the loop ahead of time
During the cycle , It can also be done through continue sentence , Skip the current loop , Start the next cycle directly
use Ctrl+C Exit procedure , Or forced end Python process
while Judge the condition :
while Judge the condition :
Loop statement
Iterators are used to iterate through a series of elements , It can not only iterate the sequence , You can also iterate over objects that are not sequences but exhibit sequence behavior . Iterators are very useful for iterating over large collections where the total number of elements cannot be known in advance . Iterators provide a unified interface to access collections , Definition iter() Method object , You can use iterators to access .
Can be next() The object that function calls and returns the next value continuously is called an iterator :Iterator.next() Function to access each object , Until the object is accessed , Return to one StopIteration abnormal . Use isinstance() We can judge whether an object is Iterator object .
be-all Iterable Both can pass iter() Function to Iterator.
try:
print("....")
except IOError:
pass
try In the middle is the code that may cause exceptions . When an error occurs , Jump to except Run seven methods to handle exceptions .
If you want to pass once except Multiple exceptions can be caught in the form of a tuple
try:
print("...") # Code
except (IOError,NameError):
pass
Or handle different exceptions differently
try:
ptint("....")
except NameError:
print("nameerror")
except IOError:
print("IOError")
notes : The exception of the parent class should be placed after its child class , Otherwise, there will never be subclass exception handling
in addition , You can also use try...except...else sentence , When try When there is no exception in the statement in ,else The code in will be executed . You can also else Followed by finally,finally The statement in , No matter try It will be executed whether there is any exception in .
Custom exception
Custom exception class inherited from Exception class , Can inherit directly , Or indirectly .