程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python

編輯:Python

The content of this article is a kind of novice tutorial python Study notes for the tutorial

Catalog

  • Python keyword
  • notes
  • Numeric type
  • character string (String)
  • Standard data type
    • Tuple
    • Dictionary
  • isinstance() and type() The difference between
  • Operator
    • Arithmetic operator
    • Logical operators
    • member operator
    • Identity operator
  • Data type conversion
  • Transfer character
  • String formatting
  • Under controlled conditions
    • while Recycling else
  • iterator
    • Custom iterators
    • generator

Python keyword

‘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’

keyword describe end Output the output results on the same line , Or add different characters at the end of the output passpass Spatiotemporal sentences , In order to maintain the integrity of the program structure ,pass Not doing anything , Generally used as a space occupying statement

notes

  1. Single-line comments : With “#” start
# Single-line comments
  1. Multiline comment : Single or double quotation marks
'''
Single quotes and multi line comments
'''
"""
Double quotes and multi line comments
"""

Numeric type

  1. integer :int
  2. Boolean :bool (bool yes int Subclasses of )
  3. Floating point numbers :float
  4. The plural :complex

character string (String)

  1. Strings using single and double quotation marks are identical
  2. Use three quotes ’’' perhaps """ You can specify a multiline string , Multiline comment
  3. Escape character :\
  4. The backslash can be escaped , Use r Can make escape ineffective , Such as :r’‘this is a line with \n’ there \n Will output directly , there r refer to row, namely row string, It means that the output string is one line
  5. Concatenate strings literally , Such as "this" “is” “string" Will automatically convert to "this is string”
  6. It can be used + Operators connect strings , Use * Operator repeats output
  7. There are two ways to index strings , From left to right 0,1,2… Start , From right to left -1,-2,-3… Start
  8. python String in cannot be changed (Number For storing values , It is not allowed to change
  9. python There is no separate character type in , A character is a character with a length of 1 Character creation of
  10. The syntax format of string interception : Variable [ Header subscript : Tail subscript : step
  11. print() The default is line feed output , add to end=" " Don't wrap , Such as print(‘test’, end=’ ')
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

Standard data type

  1. variable :List、Set、Dictionary
  2. immutable :Number、String、Tuple

Tuple

  1. Tuple Elements in cannot be modified , But it can contain mutable objects , Such as list
  2. An empty tuple :tup = ()
  3. Tuples with only one element , You need to add a comma after the element :tup = (1,)

Dictionary

Dictionary Dictionaries : Key value pair set

isinstance() and type() The difference between

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.

Operator

Be careful python There is no self increase in (++) Self inspection (–) Operator

Arithmetic operator

  1. Add :+
  2. Subtraction :-
  3. Multiplication :*
  4. division :/( Return floating point number ),//( Return integer , Rounding down )
  5. Remainder :%
  6. chengfang :**

Logical operators

Hypothetical variables a=False,b=True

Logical operators Logical expression describe andx and y And orx or y or notnot x Not

member operator

member operator describe example in Find the specified value in the specified sequence and return True, Otherwise return to Falseif (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)

Identity operator

Storage unit used to compare two objects

Identity operator describe example is Determine if two identifiers refer to the same object x is y If it is the same object referenced, return True, Otherwise return to False, Be similar to id(x)==id(y)
id(), To get the memory address of the object
is and == The difference between :is Is to judge whether two objects are the same object ,== Is to compare whether the values of two objects are equal
is not Determine whether two identifiers are derived from different objects x is not y If x and y The referenced object does not return the same object True, Otherwise return to False

Data type conversion

Data type conversion , Just use the data type as a function .

function describe int(x,[,base]) take x Convert to an integer , Default syntax :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,Set

Transfer character

Escape character describe \ Endurance \\ The backslash \a Ring the bell , The computer will ring after output \b Space \000 empty

String formatting

print(' My name is %s This year, %d' year % (' Peppa Pig ',1))
Output : My name is Peppa Pig this year 1 year

Under controlled conditions

Python Use in elif Replaced the else if.
Use a colon after each condition “:”.
Python There is no switch-case sentence .

while Recycling else

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 .

iterator

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 = " ")

Custom iterators

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

generator

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved