Learning python
-
Three kinds of quotes
- Single quotes
' '
Indicates a string. Double quotation marks can be placed inside single quotation marks - Double quotation marks
""
Represents a string. Single quotation marks can be placed inside double quotation marks - Three quotes
"' or" ""
Line breaks are supported. The other two do not support line breaksname = ''' 123
-
An escape character for a string
\n
A newline\t
Horizontal tabs\r
enter\b
Back space\a
Ring the bell\e
escape\f
Change the page\v
Vertical TAB character\ 000
空\
Line continuation operator\ \
Backslash notation\ '
Single quotes\"
Double quotation marks\oyy
Octal numbers, y represents a character from 0 to 7, for example: \012 represents a newline.\xyy
A hexadecimal number, starting with \x, in which yy stands for a character, for example, \x0a stands for a newline\other
Other characters are printed in normal format
-
About the variable
-
X,y,z = 1,2,3
-
Variable names consist of letters, underscores, and numbers
-
In administrator mode, enter Python and press Enter. Enter import keyword and press enter. Enter print(keyword. Kwlist) and press enter to display English words that cannot be used as variable names
-
Key words:
'False','None','True','and','as','assert','break','class','continue','def',
'del','elif','else','except','finally','for','form','global','if','import',
'in','is','lambda','nonlocal','not','or','pass','raise','return','try',
'while','with','yield'
-
Built-in functions (BIF) also do not have variable names:
'ArithmenticError','AssertionError','AttributeError','BaseException','BlockingIOError','BrokenPipeError','BufferError',' BytesWarning ', 'ChildprocessError, 'ConnectionAbortedError','ConnectionError,'ConnectionRefusedError','ConnectionResetError','DeprecationWarning','EOFError ','ELLipsis','EnvironmentError','Exception','False','FileExistsError','FileNotFoundError','FloatingPointError','FutureWa rning','GeneratorExit','IOError','ImportError','ImportWarning','IndentationError','IndexError','InteruptedError','IsADir ectoryError','KeyError','KeyboardInterrupt','LookupError','MemoryError','ModuleNotFoundError','NameError','None','NotADi rectoryError','NotImplemented','NotImplementedError','OSError','OverflowError','PendingDeprecationWarning','PermissionEr ror','ProcessLookupError','RecursionError','ReferenceError','ResourceWarning','RuntimeError','RuntimeWarning','StopAsync Iteration','StopInteration','SyntaxError','SyntaxWarning','SystemError','SystemExit','TabError','TimeoutError','True','T ypeError','UnboundLocalError','UnicodeDecodeError','UnicodeEncodeError','UnicodeError','UnicodeTranslateError','UnicodeW arning','UserWarning','ValueError','Warning','WindowsError','ZeroDivisionError','__build_class__','__debug__','__doc__', '__import__','__loader__','__name__','__package__','__spec__','abs','all','any','ascii','bin','bool','bytearray','bytes' ,'callable','chr','classmethod','compile','complex','copyright','credits','delattr','dict','dir','divmod','enumerate','e val','exec','exit','filter','float','format',frozenset','getattr','globals','hasattr','hash','help','hex','id','input',' int','in=sinstance','issubclass','iter','len','license','list','locals','map','max','memoryview','min','next','object',' oct','open','ord','pow','print','property','quit','range','repr','reversed','round','set','setattr','slice','sorted','st aticmethod','str','sum','super','tuple','type','vars','zip'
-
Input and output
1. A = input (‘ please input: ‘) print(a)Note:
Input accepts all strings
2.input
The inputprint
Output, print
-
Math module
import math
enter
math.pi
enter
Result PI output:3.141592653589793
Dir (math) View module contents
-
Numeric types
1. Integer Int Example: 123
Float: 0.001
- 2.1 High precision floating point calculation
-
import decimal
enter
-
-
- decimal.Decimal(
'1.01'
) – decimal.Decimal('0.9'
)Have to
Decimal('0.9'
)
- decimal.Decimal(
-
-
-
Note:
You can usedecimal
Module to do the exact calculation of floating point numbers, used when passed is astring
-
3. Boolean bool two values True (value 1) and False (value 0)
-
Numerical type calculation
1. + – * / %
Take more than
* * power operation
//aliquot
2. Symbol:! = Not equal == Equal >= Less than or equal to <= Greater than or equal to < Less than > Greater than
3. With:
and
saidand
orand
“Is true only if both sides are true4. Or:
or
saidor
“Is true as long as one side is true5. A:
not
It means to take the opposite meaning true becomes false, false becomes true -
Python operator priority
1. **
Index (highest priority)
2. ~ + -
Bitwise flip, unary plus and minus (the last two methods are called +@ and -@)
3. % * / / /
Multiply, divide, find the remainder and take the exact division
4. + -
Addition subtraction
5. >> <<
Shift right, shift left operator
6. &
A ‘AND’
7. ^ |
An operator
8. < = < > > =
Comparison operator
9. = =! =
Equal operator
10. = %= /= //= -= += *= **=
The assignment operator
11. is is not
Identity operator
12. in not in
Member operator
13. not and or
Logical operator
-
Identify the type
1.type()
The comparison operator returns a bool
-
String formatting
- %
Format placeholders
- %d
Format integer ~~ %6d Indicates the length of the character string
- %f
Format floating point (decimal) ~~ %06.2d 0 indicates padding. 2 indicates that only two decimal places are left
- %c
Format the ASCLL code ~~ %97 output the corresponding value of the ASCLL code 'a'
- %o
Octal output ~~ %8 Octal output '10'
- %x
Hex output ~~ %16 Output hex to get '10'
- %o
Octal output ~~ %8 Octal output '10'
- %e
+ +04 = '1.000000e+04'
- %r
Object uninitialized ~~ %'123' uninitialized output object gets "'123'"
- %s
Formatted string
s=’hello’ t=’kt’print('%s %s'
%(s,t)) output concatenation string to get string 'hello kt'
-
The format method of a string
'{a:.2f}'
. The format (a = 12.3333)Keep two decimal places
The output of 12.33
'{:.2%}'
. The format (0.35)It's printed as a percent sign
The output of 35.00%
'{0:x}'
.format(20)Convert to hexadecimal
The output of 14
'{b:0<10}'
= 12.3. The format (a, b = 13.35)Left-align and fill with the number 0
The output of 13.3500000
'{a:*^10}'
= 12.3. The format (a, b = 13.35)Align center
Output 12.3 * * * * * *
'{{hello {} }}'
.format(‘python’)Escape the braces
{ hello python }
'f= 'hello {0}'
.format f(‘python’)Call as a function
Output 'hello python'
-
-
Strings are usually immutable but usable
replace
The () method replaces the string, but does not modify it. It simply returns a new object, as all string methods do
-
-
-
Mutable objects: list, dict, and set
-
-
-
Immutable objects: values, STR, tuples
-
upper()
All capslower()
All lowercasecapitalize()
Uppercasetitle()
Capitalized word, title formstrip()
Remove the space on both sides- Split () String splits (‘ string ‘, times)
join()
Joining togetherstrip()
Remove the space on both sides- Find () finds the index value of an element in the string. If no element is found, -1 is returned
-
The string provides a method of determination inside
isalpha()
It’s all lettersisdigit()
It’s all numbersislower()
Judgments are all lower caseisupper()
The judgment is all caps
-
Encoding of strings
encode(encoding= '' )
Encodes a string to the specified encodingdecode( '' )
In switching back
-
Python contains the following functions:
cmp(list1, list2)
Compare the elements of two listslen()
Number of list elementsmax()
Returns the maximum number of list elementsmin()
Returns the minimum value of a list elementlist()
Converts tuples to lists
-
Conditional statements
1.if else
ifPrint ()else:
print()
ifElif: print()else:
print()
Copy the code
2. Ternary operation
print(True if a>5 else False)
Copy the code
3. The while loop
a = 1
while a<5:
print(a)
a +=1Execute in sequence until the loop endselse:
print('End of loop') ifwhileIf the following condition is True, the inner condition is addedbreakTo terminate the loop, usebreakA terminated loop is not executedelseThe content of thecontinueIt just jumps out of the current loop and executes the next loopCopy the code
4. The for loop
for i in 'python': print(I) Loop The length of the string len determines the loop numberCopy the code
P, y, T, H, o, n
for i in range(10):
print(i,end=', ')
Copy the code
The result is 0,1,2,3,4,5,6,7,8,9
The range function can take a range of integersRange (start, end, step size)
End in print sets the string to be printed after each value is printed. The default is newline
-
-
- Iterable: strings, lists, tuples, dictionaries, collections
-
for i in range(1.6.2):
print(i,end=' ')
i = 'python'
print(i,The '*')
Copy the code
The result is 1 python *
3python*
5python*
for i in range(1.20) :if i % 2= =0 or i % 3= =0:
continue
else:
print(i,end=', ')
Copy the code
The result is 1,5,7,11,13,17,19
for
Circulation andwhile
Loops can be usedbreak
andcontinue
It can also be connectedelse
, when the loop isbreak
At the end of,else
Do not perform
for i in range(1.20) :if i % 2= =0 or i % 3= =0:
continue
elif i % 15= =0:
break
else:
print(i,end=', ')
else:
print('End of loop')
Copy the code
The result is 1,5,7,11,13,17,19, and the cycle ends
List = [] Lists can hold almost any Python object
-
Take all even numbers up to 100:
-
1.
for i in range(101): if i % 2 == 0: print(i)
-
2.
list_a = [] for i in range(101): if i % 2 == 0: list_a.append(i)
-
List_b = [I for I in range(101) if I % 2 == 0]
I is the value stored in the list for I in range(101)for loop to get the value if I % 2 == 0If judgment to filter the value [] enclosed in brackets to indicate the list
-
List the list
-
-
List = [Start: end: step]
-
Three ways to add:append
(‘ single add ‘);extend
([‘ batch Add ‘,’ batch Add ‘]);insert
(1,’ add at specified location ‘)
There are three ways to delete:pop
(‘ remove one at a time ‘);remove
([‘ remove specified element ‘]);claer
(‘ One-time empty ‘)
Other methods of listing:count
(‘ number of statistical elements ‘);reverse
([‘ reverse list order, not sort ‘]);sort
(‘ Sort the elements in the list using Timsort ‘);copy
(‘ copy ‘);
-
Tuples:
(a)
The inside of the fortuples
, like a list, can also index values, but elementsYou can't change it. Once you're sure, you can't change it
. If the tuple has only one element(1)
Again, keep up with the comma,Otherwise it will be treated as an element
Rather thantuples
unpacking
: Tuples can be assigned to more than one variable at a time, as long as the number of variables does not exceed the length of the variable*
A sign can take multiple elements and form a list
Ex. :
A = b = (1) ([' hello, 'the python,'! ']) = c ([6,8,10]) tuple_d = a, c print *, b * (tuple_d)Copy the code
Results for ((1), ‘hello,’ python ‘, ‘! ‘,6,8,10) can be checked with type (tuple_d)
-
Dictionary:
Dictionaries are defined as key-value pairs
1. dict_a = {} An empty dictionary
2. dict_b = dict(a=1,b=2) Use the dict function to define a dictionary
3. dict_c = {‘a’:1,’b’:2} It's the same as dict_b
Add, delete, modify and check the dictionary
- through
key
To the values,key
If it does not exist, an error is reported - through
get()
Method to evaluate,key
Does not exist, and no error will be reported - through
setdefault()
Method to find whenkey
If it exists, returnvalues
Value if key does not existAdd key-value pairs
- through
update()
Methods can be updatedkey
The value of, ifkey
There is no,Add key-value pairs
keys()
Method to get all of themkey
values()
Method to get all of themvalues
items()
Method to get all of themKey/value pair
pop()
Method to delete the specifiedkey
popitem()
Method to delete the last one in the dictionaryKey/value pair
clear()
Method to delete all elements in a dictionary
Operation of set
- Intersection: used by the same elements in two sets
set()
said&
- Union: The combination of different elements of two sets
|
- Difference set: Two sets minus the same elements in both sets
-
Create an empty collection must be usedset()
Rather than{}
Because the{}
Is used to create an empty dictionary.
Collection of add delete change check
- Add () adds elements
- Update () adds parameters that can be lists, tuples, dictionaries, etc
- Pop () randomly removes an element from the collection
- Remove () removes elements