One 、PYTHON The elements in
1. The basic elements
- Operator : + - * / % wait
- The order of operations : First, To add and subtract Brackets first
- Variable : It's a label :, A letter that begins with a non number 、 Numbers 、 Underline composition , Its content can be numerical 、 character string 、 list 、 Tuples and dictionaries .
- The number , Is the number . Such as a = 100
- character string , It's a pair of quotation marks 、 Or in single quotation marks , Just put it in quotation marks , It's just a string .
Such as : b = ”Hello World”
100 Numerical value , and ”100” Is string .
- Escape character
\t Express tab \n Express in That's ok
- %s placeholder , use % After the variable replacement
Such as :
a = 100
b = ” HelloWorld ”
print ” point = %s \n \” %s \” ” % (a, b)
Print out :
point=100
” Hello World ”
2. list
for example :
c = [1,2,3,4,5,6,7]
d = [” Zhang San ”,” Li Si ”,” Wang Wu ”]
e =[1,2,3,”4”,”5”,d]
- use List name [ Reference no. ] Index the elements in the list
d[0] Represents a list d The zero element in “ Zhang San ”
- Use the list name [ rise : stop ] It means slicing , Cut out the corresponding elements from the list Before closed after opening
c[0:2] Cut out [1,2]
c[ : ] Cut out [1,2,3,4,5,6,7]
- Use the list name [ rise : stop : step ] Slice with step size , Step size has direction .
Such as c = [1,2,3,4,5,6,7] , If you cut out [5,4,3,2] use c[4 :0 :-1] ; Cut out [5,4,3,2,1] use c[4 ::-1] ; Cut out [6,4,2] use c[-2 ::-2]; Start from the second to the last and cut all the way to the end , step -2
- modify : List name [ Reference no. ] = The new value
- Delete :del List name [ Reference no. ]
- Insert : List name .insert( Insert position index number , The new element )
- If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming
3. Tuples
Once the definition cannot be changed
f=(1,2,3)
4. Dictionaries
- There is... In the dictionary { key : value , key : value , key : value } n Key value pairs
dic={1:”123”,”name”:”zhangsan”,”height”:180}
- Use the dictionary name [ key ] The values in the index Dictionary
dic[”name”] A dictionary dic In the key ”name” Corresponding value ”zhangsan”
- modify : Dictionary name [ key ] = The new value
- Delete :del Dictionary name [ key ]
- Insert : Dictionary name [ New key ] = The new value
Two 、python grammar
Python The code is indented with four spaces to represent the hierarchy
- Loop statement
- for Variable in range ( Starting value , End value ) for example :
- for Variable in List name Such as :
M = ['a', 'p', 'o']
for i in M: - while Conditions :
- Terminate the cycle with break
- turtle modular
import turtle # Import turtle model block
t = turtle.Pen ( ) # use turtle Module Pen class , An example is called t The object of
t.forward ( Pixel point ) # Give Way t How many pixels forward
t.backward ( Pixel point ) # Give Way t How many pixels forward t.left ( angle ) # Give Way t How many angles to turn left t.right ( angle ) # Give Way t How many angles to the right t.reset ( ) # Give Way t complex position
- function
-
function (function): Well organized , Reusable , A piece of code used to implement a single or associated function .
such as input() It's just a function , You can use functions directly , You don't have to redefine how to receive input from the console every time , So the function is to help realize code reuse . -
Defined function :def Function name ( Parameter table ):
Letter Count body The parameters in brackets can be empty if they are not needed - Using functions : Function name ( Parameter table )
Such as :input("please input your class number:")
Definition :def hi_name(yourname):
print ”Hello %s”%yourname Use :hi_name(”zhangsan”)
Will be output :Hello zhangsan - Function return value : return
def add(a,b):
return a+b
c=add(5,6) # c To be an assignment add The return value of 11 - Built-in functions :python Functions that come with the interpreter
Such as :abs(-10) return return 10
- modular
modular (module): It's a Python file , With .py ending , Contains Python Function, etc . First import , Reuse , With modules . Function name call .
for example :
import time
time.asctime ( )
Output :'Tue Jan 1621:51:06 2018'
- package
Contains multiple modules , Such as :from PIL import Image
- Variable scope
local variable : Variables defined in functions , It's only in functions , The end of function execution cannot be used again . Global variables , A variable defined before a function , Usually defined at the top of the entire code , Global availability .
If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming
3、 ... and 、 class 、 Object and object-oriented programming
- class (class): A collection of objects with the same properties and methods . It defines the properties and methods that are common to each object in the collection . Object is an instance of a class . Birds of a feather flock together , Classes are molds that instantiate objects .
- real example turn : Yes like = class () Such as :t = turtle.Pen()
- object : Is an entity instantiated from a class , The object really exists , Finish the specific work .
- object-oriented : The programmer modifies the optimization class over and over again , Class instantiates the object , Object calls the function in the class to perform the specific operation .
For example, in the figure above , There are animals 、 Mammals and cats . Animals are a class , They have a common function : breathing 、 Moving and eating . Mammals are also a class , They're a subclass of animals , On the basis of animals, it has the function of feeding milk . Cats are a subclass of mammals , Cats have the function of catching mice on the basis of mammals .
The first letter of a class is often capitalized , such as Animals、Mammals and Cats The initials of are all capitalized . The right side of these classes lists the functions that each class has : Like breathing 、 Moving and eating are the functions of animals , To express in the form of a function in a computer . Feeding is a mammalian function , It's a function of the mammalian class . Catching mice is a function of cats , It's a cat function .
√ The above class is the parent of the following class ; The following class is a subclass of the above class
√ Subclass instantiated objects , You can use functions and variables of itself and its parent class
- The definition of a class :
class Class name ( Parent class name ) :
pass
If there is a parent class , Write it in brackets after the class name ; If there is no parent class , You can stop writing brackets . Use the key words pass Take a place , After that, we use the concrete function to complete the class .
give an example :classAnimals:
pass
classMammals(Animals):
pass
classCats(Mammals):
pass
- When you define a function in a class , The syntax states that the first parameter must be self .
- init__ function , It runs automatically when a new object is instantiated , Used to assign initial values to new objects .
(1) The cat class is instantiated into a name called kitty The object of ,kitty It has its own characteristics , For example, you have 10 Spots :
kitty = Cats(10) # Run on instantiation init function , to spots assignment , inform kitty Yes 10 Spots
print”kitty.spots” # Print out 10
(2)kitty You can do specific work , Like catching mice :
kitty.catch_mouse()# Object to run functions , You have to use objects . Function name , Call the function in the class
# Will run print ”catch mouse” So print it out catch mouse
- Object calls the function in the class , use object . Function name ;
Object calls the variables in the class , use object . Variable name . - When defining a function within a class , Such as calling functions and variables of its own or parent class , Must use self. guide , Should be written as self. Function name or self. Variable name .

Code validation :
- Add :
Python Although there is no access control keyword in , for example private、protected wait . however , stay Python In the encoding , There are some conventions for access control .
Underline 、 Double underline 、 Double underline description :
_foo: What begins with a single underscore is protected Variable of type , That is, the protection type can only be accessed by itself and its subclass , Cannot be used for frommodule import *
foo: Double underscores indicate private types (private) The variable of , Only the class itself can be allowed to access .
foo__: Double underscores define the special method , similar init() And so on. .
Four 、 File operations
- File write operation
import pickle
open : File variables = open(” File path file name ”, ”wb”)
save :pickle.dump( Variable to be written , File variables )
Turn off : File variables .close()
Code validation :
- File read operation
import pickle
open : File variables = open(” File path file name ”, ”rb”)
take : Put the variable of content =pickle.load( File variables )
Turn off : File variables .close()
Code validation :
If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming