The content of this article is a kind of novice tutorial python Study notes for the tutorial
‘False’, ‘None’, ‘True’, ‘__peg_parse__’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’’, else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’
# Single-line comments
'''
Single quotes and multi line comments
'''
"""
Double quotes and multi line comments
"""
str='123456789'
print(str) # Output string :123456798
print(str[0:-2]) # Output from the first to the penultimate on the left 3 individual :1234567
print(str[2]) # Output the third character :3
print(str[2:5]) # Output the third to fifth characters ( Include third ):345
print(str[5:]) # Output from the sixth character ( Contains the sixth ):6789
print(str[1:7:2]) # Output from the second character to the eighth character , In steps of 2:246
prtin(str * 2) # Output twice :123456789123456789
print(str + 'test') #+ String splicing :123456789test
print('test \n test') # Escape character \n Line break :test( Output after line break )test
print(r'test \n test') # Invalid escape character output as is :test \n test
Dictionary Dictionaries : Key value pair set
isinstance() Do not distinguish between classes that have inheritance relationships , Such as :B Inherited from A,isinstance(B(),A) return True.type() Then the class with inheritance relationship is distinguished , Such as :type(B())==A, return False.
Be careful python There is no self increase in (++) Self inspection (–) Operator
Hypothetical variables a=False,b=True
if (a in list)
not in The specified value was not found in the specified sequence. Return True, Otherwise return to Falseif(a not in list)
Storage unit used to compare two objects
x is y
If it is the same object referenced, return True, Otherwise return to False, Be similar to id(x)==id(y)
x is not y
If x and y The referenced object does not return the same object True, Otherwise return to FalseData type conversion , Just use the data type as a function .
class int(x,base=10)
Parameters base As a hexadecimal number , Default to decimal float(x) take x Convert to a floating point number str(x) take x Convert to string repr(object) take object Convert to a form for the interpreter to read , Such as print List,Setprint(' My name is %s This year, %d' year % (' Peppa Pig ',1))
Output : My name is Peppa Pig this year 1 year
Python Use in elif Replaced the else if.
Use a colon after each condition “:”.
Python There is no switch-case sentence .
example :
count = -2
while count > 0 :
print(count , " Greater than 0 ")
count += 1
else :
print(count , " Less than 0")
for Cycle the same thing .
Use... In loop statements else sentence , In the exhaustive list (for loop ) Or the condition becomes false(while loop ) Execute when the loop terminates , But the loop is break When does not perform .
Iteration is a way to access element combinations .
An iterator is an object that remembers the traversal position .
The iterator accesses from the first element of the traversed object , Until all elements are accessed , Iterators only go forward, not backward .
There are two basic ways to iterator iter() and next().
example :
list = [1,2,3,4]
it = iter(list) // Create iterator it
print(next(it)) // The next element of the output iterator 1
Iterators can use for Loop through
list = [1,2,3,4]
it = iter(list)
for x in it:
print(x, end = " ")
A custom iterator needs to implement two methods :__iter__(),__next_()
__iter_() Returns a special iterator ( Custom content ), This iterator object implements __next__() Method and pass StopIteration The exception marks the completion of the iteration
Create an iterator that returns a number , The initial value is 1, Step by step 1
Class TestNumber:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
testNumber = TestNumber()
it = iter(testNumber)
count = 5
while count > 5:
print(next(it))
count += 1
Used yield The function of the is called the generator (generator), The difference from ordinary functions is , A generator is a function that returns an iterator , Can only be used for iterative operations , Simply understand that a generator is an iterator .
During the call generator run , Every encounter yield when , The function pauses and saves all information about the current run , return yield Value , And next time next() Method to continue execution from the current location .
summary : Call contains yield The function of returns an iterator , A generator is understood as generating an iterator .
Use yield Realization of Fibonacci series :
import sys
def fibonacci(n):
a,b,count = 0,1,0
while True:
if count > n : // Exit after more than the number of cycles
return
yield a // Record and return the current a Value 0,1,1,2,3,5,8,13,21,34,55
a,b = b, a+b
count += 1
f = fibonacci(10) // amount to f = [0,1,1,2,3,5,8,13,21,34,55]
while True:
try:
print(next(f), end=" ")
except StopIteration:
sys.exit()
// Output results :0 1 1 2 3 5 8 13 21 34 55
If you have any questions, please chat privately or send an email ([email protected]) Discuss together