Variables in Python are written similarly to variables in C;
Python program writing structure uses indentation, discarding curly braces;
if(Conditional statement 1):
Execute statement block
elseif(Conditional statement 2):
Execute statement block
else:
Execute statement block
while loop condition:
Loop statement body
for target in expression:
Loop statement body
The result of the expression will be combined with the target
Step function
range(x,y,z)
x: Start
y: end (y-1)
z: step size
Jump out of the current structure
End the operation of this loop body
>>> num =[1,2,3,4,5]//List creation>>> num //List output[1,2,3,4,5]>>> num =['Hello','Hello there',666]>>> num //The list supports various types, and all characters except numbers need to use single quotes['Hello','Hello there',666]
>>> num.append(6)>>> num
[1,2,3,4,5,6]
>>> num.extend([7,8,9])>>> num
[1,2,3,4,5,6,7,8,9]
append() is to add a single element, which is a simple expansion;
And extend() is to splice the original list and the list you want to add into a new list
>>> num.insert(0,0)//Add element 0 at index 0>>> num
[0,1,2,3,4,5,6,7,8,9]
>>> num.pop()9>>> num.pop(0)0>>> num
[1,2,3,4,5,6,7,8]
>>> num =[1,2,3,4,5,6,7,8]>>> num
[1,2,3,4,5,6,7,8]>>> del num[7]>>> num
[1,2,3,4,5,6,7]>>> del num
>>> num
Traceback(most recent call last):
File "<pyshell#19>", line 1,in<module>
num
NameError: name 'num' is not defined
If an error is reported: num does not exist
Our previous del statement and pop() function rely on the index of the list to delete the elements under the index, and remove() does not rely on the index, but deletes according to the specific content of the element.
>>> num =['Hello','Hello there',666]>>> num
[' Hello','Hello there',666]>>> num.remove(666)>>> num
[' Hello','Hello there']>>> num.remove('Hello there')>>> num
[' Hello']
To output or display or copy only a part of the data elements of a list is the so-called list fragmentation
>>> num =['HUAWEI',"CHINA",'Mirror','XIAOMI']>>> num
[' HUAWEI','CHINA','Mirror','XIAOMI']>>> num[0:1]['HUAWEI']>>> num[0:2]['HUAWEI','CHINA']>>> num[0:4]['HUAWEI','CHINA','Mirror','XIAOMI']>>> num[:2]['HUAWEI','CHINA']>>> num[:]['HUAWEI','CHINA','Mirror','XIAOMI']>>> num[2:]['Mirror','XIAOMI']
Observe carefully and find that the sliced [x:y] is the range of left-closed and right-opened (principle) [Many closed problems related to the range in python are the principle of left-closed and right-opened]
At the same time, the fragmentation mechanism also supports the omission of range values; that is, if the left is empty, it will start from 0, if the right is empty, it will end at the last element, and if both left and right are empty, all elements will be output;
Everyone thinks that fragmentation has only two parameters?
Sharding has three parameters ==> [x:y:z]
x: Start
y: end
z: Step length (that is, the number of increments is z, which can also be understood as the concept of arithmetic in mathematics)
>>> num =[]//Create an empty array>>>for i inrange(1,10):
num.append(i)>>> num
[1,2,3,4,5,6,7,8,9]>>> num[0:10:2][1,3,5,7,9]
>>> list =[1,2,3,4]>>> copy = list
>>> copy1 = list
>>> copy2 = list[:]>>> copy1
[1,2,3,4]>>> copy2
[1,2,3,4]
It can be seen from the above that the result of direct copying of list is the same as that of list[:] fragmented copying, but in fact it is secretly impatient!
>>> list.append(5)>>> copy1
[1,2,3,4,5]>>> copy2
[1,2,3,4]
Add an element to the original source list append() and find that the contents of copy1 and the list source list are not changed together (append() operation)
copy1 = list: belongs to the memory address of the list to copy1,
copy2 = list[:]: belongs to the value of list to copy2
The list supports comparison operations of comparison operators:
>>> list1 =[123]>>> list2 =[234]>>> list3 =[123]>>> list1 < list2
True
>>> list1 <= list3
True
>>> list1 == list3
True
>>> list1 != list2
True
>>> list1.append(234)>>> list2.append(123)>>> list1
[123,234]>>> list2
[234,123]>>> list1 > list2
False
The comparison of two lists is based on the size of the ASCII value. If two elements are encountered, the first is compared, and if the first is the same, the second is compared.
>>> str1
[' HUAWEI']>>> str2
[' CHINA']>>> str1 + str2
[' HUAWEI','CHINA']>>> str1 *3['HUAWEI','HUAWEI','HUAWEI']>>> str1 = str1 +str2
>>> str1
[' HUAWEI','CHINA']>>> str1[1]*3'CHINACHINACHINA'
>>> str1
[' HUAWEI','CHINA']>>>"CHINA"in str1
True
>>>" CHINA" not in str1
False
>>> str =["H","U","A","W","E","I"]>>> str
[' H','U','A','W','E','I']>>> str.index("I")5>>> str.index("K")//Element does not exist save Traceback(most recent call last):
File "<pyshell#4>", line 1,in<module>
str.index("K")
ValueError:'K' is not in list
>>>
>>> list
[3,4,5,2,5,66,7,2,5,7]>>> list.count(5)3
>>> list
[3,4,5,2,5,66,7,2,5,7]>>> list.reverse()//Reverse arrangement>>> list
[7,5,2,7,66,5,2,5,4,3]>>> list.sort()//Ascending>>> list
[2,2,3,4,5,5,5,7,7,66]>>> list.reverse()//Reverse arrangement (srot+reverse ==>Descending)>>> list
[66,7,7,5,5,5,4,3,2,2]
A tuple can be understood as a list that cannot be changed once defined.
>>> tuple =(1,2,3,4,5)>>> number =[1,2,3,4,5]>>>tuple(1,2,3,4,5)>>> number
[1,2,3,4,5]
Tuple is a tuple, number is a list;
Can be found; the definitions of the two are different
A tuple is a set of list data composed of parentheses, and a list is a set of data composed of square brackets
The access method of a tuple is the same as that of a list. The elements of a tuple are mainly accessed through the index of the tuple. Like a list, it can be accessed through sharding (slicing).
>>> tuple(1,2,3,4,5)>>> tuple[2]3>>> tuple[3]4>>> tuple[:](1,2,3,4,5)
>>> tup =()>>> num =[]>>>type(tup)<class'tuple'>>>>type(num)<class'list'>
Many times, the list data defined by parentheses is considered to be a tuple, but it is not!
>>> del tup
>>> tup
Traceback(most recent call last):
File "<pyshell#14>", line 1,in<module>
tup
NameError: name 'tup' is not defined
>>> tup =1,2,3,4>>>type(tup)<class'tuple'>
That's right, the list data without parentheses is also a tuple.
The characteristics of defining tuples are: comma
>>>(6)*636>>>(6,)*6(6,6,6,6,6,6)
So when defining a tuple, a comma is needed to tell the program that this is a tuple
>>> tup =(1,2,3,)>>>type(tup)<class'tuple'>
This is the most standard definition method. Why?
The functions of tuples and lists are almost the same except for data changes. The data of a tuple cannot be changed, but tuples and tuples can be spliced
>>> tup(1,2,3)>>> tup = tup[:3]+4,+5,Traceback(most recent call last):
File "<pyshell#28>", line 1,in<module>
tup = tup[:3]+4,+5,
TypeError: can only concatenate tuple(not "int") to tuple
>>> tup = tup[:3]+(4,)+(5,6,)>>>tup(1,2,3,4,5,6)
tup uses splicing to update the tup tuple data;
note:
Here when splicing, the content of the splicing is marked with brackets and commas to indicate that this is a tuple data, otherwise it will be regarded as a character or numeric data by the program.
The comma is the symbol definition of a tuple
>>> tup = tup[:2]+ tup[4:]>>>tup(1,2,5,6)
The elements that need to be deleted are covered by the splicing method to achieve the purpose of deleting the elements.
The data of tuples is unchanged, but tuples can be spliced freely like lists:
Use the slice at the end to add elements to the element (note the comma mark of the tuple element)
Use the method of slicing and splicing to cut and delete the content before and after the element is spliced into a new tuple
>>> char ="HUAWEI">>> str ='XIAOMI'>>> char
' HUAWEI'>>> str
' XIAOMI'
Single and double quotes can be used to create strings
>>> str = str[:3]+"-"+ str[3:]>>> str
' XIA-OMI'
The modification of a string is similar to a tuple, and the content of the string is changed by means of slicing and splicing.
ps: It is to reconstitute a new string to a new string variable, so it needs to be assigned
>>>'{0}- {1}={2}'. format('XIAOMI','HUAWEI','CHINA')'XIAOMI-HUAWEI=CHINA'
As can be seen from the code, the content of the curly brackets in the string is the parameter value index content corresponding to the format method. In layman's terms: the index in the curly brackets will call the corresponding parameter value in the format to form a string. {The parameter in format is called: positional parameter}
>>>'{ x}-{h}={c}'.format(x='XIAOMI',h='HUAWEI',c='CHINA')'XIAOMI-HUAWEI=CHINA'
Format symbol | Description |
---|---|
%c | formatting characters and ASCII |
%s | format string |
%d | formatted integer (decimal) |
%o | Format unsigned octal |
%x 、%X | format unsigned hexadecimal (lowercase, uppercase) |
%f | Format floating point numbers |
%e 、%E | format the floating point number in scientific notation |
The above is a common format symbol operation; it is similar to the C language.
'[ Format operator]'%[Content that needs to be formatted]
>>>' %c'%99'c'
The formatting operation is expressed as: percent sign ==> %
Parameter command | Description |
---|---|
mn | m is the minimum width, n is the number of digits after the decimal point |
- | Align Left |
+ | Show plus before the certificate |
# | Displayed in octal and decimal results respectively: 0o and 0x/0X |
0 | Fill the space with "0" before the number |
Escape character | description |
\ ' | Single quote |
\ " | Double quotes |
\ a | System beeps |
\ b | Backspace |
\ n | newline |
\ t, \v | tab character (8 spaces) |
\ f | Form feed |
\ r | Carriage Return |
\ | Backslash | |
\ 0 | Represents a null character |
>>> list =list((1,2,3,4))>>> list
[1,2,3,4]>>> list =list("HUAWEI")>>> list
[' H','U','A','W','E','I']
>>> tuple =tuple("HUAWEI")>>>tuple('H','U','A','W','E','I')>>>type(tuple)<class'tuple'>
>>> s =str(1)>>> s
'1'>>> type(s)<class'str'>>>>tuple(s)('1',)
>>> num =[1,2,3,5,6,7]>>>len(num)6
>>> num =[1,2,3,5,6,7]>>>len(num)6>>>max(num)7>>>min(num)1
>>> num =[1,2,3,5,6,7]>>>sum(num)24
>>> num
[12,24,33,32,243,3,6,23,15,7,6,5,3,2,1]>>> sorted(num)[1,2,3,3,5,6,6,7,12,15,23,24,32,33,243]>>> num
[12,24,33,32,243,3,6,23,15,7,6,5,3,2,1]>>> num.sort()>>> num
[1,2,3,3,5,6,6,7,12,15,23,24,32,33,243]
In the code, we compared with the previous sort() and found
sorted(): returns the result in ascending order but does not change the original data
sort(): sort the source list in ascending order
>>> list =list((2,4,67,3,7,3,8))>>>for i inreversed(list):print(i,end='-')8-3-7-3-67-4-2-
It can be seen that the reversed() method will output an iterable sequence in reverse iteration
Two-tuple: A tuple with an element of 2 constitutes an iteration object, and each two-tuple is composed of the index of the iteration parameter and the corresponding element.
>>> for i inenumerate(list):print(i)(0,'H')(1,'U')(2,'A')(3,'W')(4,'E')(5,'I')
Return a tuple of iterable parameters
>>> list
[2,4,67,3,7,3,8]>>> str
[' H','U','A','W','E','I']>>>for i inzip(list,str):print(i)(2,'H')(4,'U')(67,'A')(3,'W')(7,'E')(3,'I')
The meaning of the function is to encapsulate the required and repeated function code in an object function, which can be called directly when needed.
def out():print("Hello,World!")print("I am Mirror")out()//Call out function
Hello,World!
I am Mirror
When the function is defined, you can add parameter settings in parentheses to set the parameters for the function. When calling the function, you will be required to pass in the parameters. The function body can also use this parameter value for work.
def name(s):print(s)
def sum(x,y):print(x+y)name("Mirror")sum(1,2)================ RESTART ================
Mirror
3
The function can receive zero or more parameter values. When the function is defined, the data type of the parameter can be undefined
def name(s):return"I am {0}".format(s)
def sum(x,y):return"SUM = {0}".format(x+y)print(name("Mirror"))print(sum(1,2))================ RESTART================
I am Mirror
SUM =3
From the parameters of the above example, the parameter setting and passing are recognized, but what if we don’t know how many data parameters we pass?
Under normal circumstances, the triple quotation marks at the beginning of the quotation mark will not be printed out, but it will still be stored, which is very similar to the function of the comment. We can get the content in the triple quotation when calling to understand the function of the function
def sum(x,y):"""Return x,the sum of y"""return"SUM = {0}".format(x+y)print(sum.__doc__)================ RESTART ================
Return x,the sum of y
def sum(x,y):"""Return x,the sum of y"""return"SUM = {0}".format(x+y)print(sum(x=1,y=2))
Use the name of the formal parameter as a keyword, and use the "assignment" mode to pass the actual parameter to the specified parameter
def sum(x=1,y=2):"""Return x,the sum of y"""return"SUM = {0}".format(x+y)print(sum())
Default parameter: The function defines the parameter and sets a default parameter to the parameter at the same time. If the function is called when the actual parameter is received, the default parameter of the parameter is used to run
Going back to the formal parameters raised about not knowing the passing parameters:
From the parameters of the above example, the parameter setting and passing are recognized, but what if we don’t know how many data parameters we pass?
At this time, we need to set a variable parameter (parameter):
def sum(* s):print(len(s))print(type(s))sum(1,2,3,4,5,6,7)================ RESTART ================7<class'tuple'>
Observation and analysis show that: the formal parameter represented by the asterisk will automatically compress the received actual parameter sequence into a "tuple", we can only pass a single (number, character, string) parameter when no variable parameter is used
>>> dict ={1:10086,"a":"CHINA"}>>> dict
{1:10086,' a':'CHINA'}>>> dict[1]//According to Key index and return Value10086>>> dict["a"]'CHINA'
The signature feature of a dictionary is: a sequence of key-value pairs surrounded by curly braces
>>> del dict
>>> dict.fromkeys((1,2,3)){1: None,2: None,3: None}
>>> dict
{1: None,2: None,3: None}>>> dict.keys()dict_keys([1,2,3])
>>> dict.values()dict_values([None, None, None])
>>> dict.items()dict_items([(1, None),(2, None),(3, None)])
>>> dict
{1:10086,' a':'CHINA'}>>> dict.get("a")'CHINA'>>> dict.get(1)10086>>> dict.get("CHINA")>>> dict.get(112)
get() queries a key, if it does not exist, it will not return an error! You can use in/not in to determine whether it exists
>>> dict.clear()>>> dict
{}
ps: is to empty the content, not to delete
>>> dict
{1:10086,' a':'CHINA'}>>> c ={}//Define an empty dictionary>>> c
{}>>> type(c)<class'dict'>>>> c = dict.copy()>>> c
{1:10086,' a':'CHINA'}
>>> dict ={1:10086,"a":"CHINA"}>>> dict.pop(1)10086>>> dict
{' a':'CHINA'}>>> dict ={1:10086,"a":"CHINA"}>>> dict.popitem()('a','CHINA')>>> dict
{1:10086}
>>> dict.update({2:2019})>>> dict
{1:10086,' a':'CHINA',2:2019}
>>> dict1 ={}>>> dict2 ={1,2,3,4,5}//Collection creation>>>type(dict1)<class'dict'>>>>type(dict2)<class'set'>
The characteristics of the collection can be found by comparing the collection with the dictionary:
The set is a comma-separated sequence using curly braces but not applicable key-value pairs
>>> set={1,2,3,4,5,6}
>>> set1
{1,2,3,4,5,6}>>> for i in set1:print(i,end=" ")123456
Logo | Description |
---|---|
r | Open the file as read-only |
w | Open file for writing |
x | If the file exists, an exception will be thrown |
a | Open for writing, existing files can be added |
b | Open file in binary |
t | Open as text |
+ | Read and write mode |
U | Universal newline support |
open(): used to create a file object so that other operations can use the file object
os module; import os import os module
Objects can be stored on disk in the form of files; it is a simple persistence function
All data types of python can be serialized and stored on disk using prckle()
When assert is testing the program, insert checkpoints in the code
>>> list =['Mirror']>>> assert len(list)>0>>> list.pop()'Mirror'>>> assert len(list)>0Traceback(most recent call last):
File "<pyshell#3>", line 1,in<module>
assert len(list)>0
AssertionError
Assert assertion: When the condition behind the statement is satisfied, the assert will not be compiled. If the assertion condition is satisfied, an error will be reported in the program.
As in the above code program: there is an element in the original list, and assert does not report an error, but after the pop method pops up (deletes) the element, an error will be reported if the assert condition is not met.
try:
examination range
except exception[as e]:
How to deal with an exception after detection
finally://Optional
Code block
>>> try:
file =open("a.txt")
file.close()
except OSError:print("Error")
Error
For example, the program in the example detects that an OSError error occurs when calling the file file object, and executes the error (abnormal) code execution block
>>> try:
file =open("a.txt")
file.close
except OSError as e:print(str(e)+"Error")
except TypeError as e:print(str(e)+"Error")[Errno 2] No such file or directory:'a.txt'Error
As above; use the as error method to write the error information into the e variable, and output the error information in the type of str; at the same time, it is found that a variety of different error types and error output can be defined.
Exception: the base class of all exceptions (can receive exceptions of any kind)
AssertionError: The assert statement failed (assert condition is not established)
AttributeError: Access an attribute that an object does not have (the object attribute does not exist)
IOError: Input and output operation is abnormal
ImportError: Cannot import module or package (path error, etc.)
IndexError: Index exceeds sequence boundary
KeyError: access key that does not exist in the dictionary
KeyboardInterrupt: Ctrl+C is triggered
NamError: The object used has no variables
SyntaxError: Code logic syntax error
TypeError: Object type and statement requirements do not match
UnboundLocalError: Global variable exception
ValueError: The value passed in is abnormal
ZeroDivisonError: Trigger division by zero exception
Class: class Class name:
Object: def method name ():
A program can be composed of multiple classes, and a class is composed of multiple object methods;
Self keyword: object parameters representing oneself
There is only one difference between class methods and ordinary functions: they must have an additional parameter name, but you cannot assign a value to this parameter when calling this method. Python will provide this value. This special variable refers to the object itself, named: self;
As long as an object is instantiated, this method will be automatically called before the object is created; the parameter parameters will also be automatically passed into the method; the method can be rewritten to achieve the initialization operation
classPotate:
def __init__(self.name):
self.name = name
def kick(self):pirnt(self.name)
public: public, public
private: private
The above are C++ and Java methods;
Represent private attributes in Python: the first two underscores "__" in the variable name
class name(Inherited class):
Python supports multiple inheritance, that is, a class inherits multiple parent classes; [not recommended]
Recommended Posts