A basic knowledge of the python language
1. Initial understanding of python
1.1 Basic concepts
- Python is aExplanatory、object orientedhigh-level programming language.
- Python is an open source, free, interactive, and cross-platform portable scripting language.
1.2 Birth and development
- In 1991, the first Python compiler (and interpreter) was born. It is implemented in C language and can call C library (.so file). From birth, Python already has: classes, functions, exception handling, core data types including tables and dictionaries, and a module-based extension system.
- In 2000, Python 2.0 was released by the BeOpen PythonLabs team, which added a memory recovery mechanism and established the Python language.
- In 2008, Python 3 was released under unexpected circumstances, with a complete overhaul of the language and no backward compatibility.
python 3.0 and python 2.0 are not compatible with each other.
1.3 Disadvantages
- Slow operation: small and medium-sized projects are optional, and C++ is preferred for large-scale projects.
- Code cannot be encrypted.
1.4 Typical applications
Games, desktop software, automation scripts, web development, scientific computing, server software.
2 use of python
2.1 Using the command line
In the command line, use python to enter the running environment of python, and use python + file name to read the file.
2.2 Use of Pycharm
Modify the font style and Python Script template in settings, the template requirements are as follows:
#-*- codeing = utf-8 -*-
#@Time:${DATE} ${TIME}
#@Author:
#@File: ${NAME}.py
#@Software:${PRODUCT_NAME}
3 Grammar
3.1 Variables and types
When assigning a value (such as a='ABC'), the Python interpreter does two things:
Create a string of 'ABC' in memory
Create a variable named a in memory and point it to 'ABC'
3.2 Identifiers and keywords
The keyword means that in the current version, it cannot be used as some naming of variables.
3.3 String formatted output
Click directly on w3school to find the formatting characters.
%d, used for decimal integer placeholder;
%s, used for str placeholder, there are multiple strings that need placeholders, use a %("xx", "xx")
3.4 Others
- input
input
and outputprint
- Mandatory type conversion:
int(“123”)
- operator
- conditional control statement
if True:
print("True")
elif:
print("False")
The elif here is equivalent to else if, and else can also be used at the end.
- The loop statement
range indicates the range, and you can input the upper and lower limits of parameters, step size orlen() extracts the length; You can also directly follow the list name after in to print the complete list.
for i in range():
while True:
break, continue, pass (empty statement, used for placeholder, do nothing)
- Introduce the library import
import import the entire module of the library
form...import... import a function from a module
4 strings, tuples, lists, dictionaries
4.1 Strings
- Single quotes, double quotes, and multiple quotes are equivalent to words, sentences, and paragraphs, respectively. The difference is whether there are the same single quotes or double quotes inside the printed string.
- backslash \It means escaping special characters; but if the string is preceded by + r, such as r"xxxx", the escaping function will disappear (often used in crawlers).
- There are dedicated interfaces , APIs, class libraries, and functions indata processingprocess strings.
Commonly used string processing functions:
isalnum(), determine whether the strings are all letters + numbers
isalpha(), determine whether the strings are all letters
isdigit(), determine whether the strings are all numbers
isnumeric(), determine whether the strings are all numbers
join(seq) , use seq as the separator, combine the strings
len(string), return the string length
Istrip(), intercept the space on the left or the specified character
rstrip(), intercept the space at the end of the right
split (str = "", num = count), to str is the delimiter, intercept num segment substring
4.2 List List
- define an empty list
list = [ ]
- The list is separated by [ ]
- The element types in the list can be different, which is the data structure of most collection classes
- 0 means the start position, -1 means the end position
Common operations on lists :
1. "Traverse":
for name in list:
2. "Increase":
append
(append to end of list)
If it is another list, using append will form the nesting of the list, then you need to use extend
extend
(append new list)insert
(insert at specified position, insert element)
3. "Delete":
del list[0]
, delete according to the subscriptlist.remove()
, removing the first match foundlist.pop()
, pop the last element at the end
4. "Change":
- Modify according to subscript
5. "Check":
in、not in
, can only return True or Falselist.index("xx",1,3)
, returns the subscript of the matching value, and can specify the search range (left closed and right open)
6. "Row":
- sort` (sort)
reverse
(reverse output in reverse order)
4.3 Tuple Tuple
- The tuple is represented by ()
- Elements in a tuple cannot be modified, but can contain mutable objects such as lists
Note: To define a tuple with a length of 1, it must also be written as
t1 = (1,)
Operations on tuples:
1. "Increase":
- Using the + operator directly is equivalent to creating a new tuple and concatenating it.
2. "Delete"
del Tup
, will delete the entire tuple including the definition of the variable
3. "check"
- slice access
4.4 Dictionary dict
- Representation:
dict = {“key”:value}
- key-value pairs (key-value)
- Mandatory conversion: As long as there are one-to-one tuples in the list, it can be converted into a dictionary, for example:
dict([(1,2),(2,3)])
Dictionary operations:
1. "Check":
dict.get(“value”,“默认值”)
The default value is that if the corresponding key is not found, a default value will be returned.
- The keys, values, and items methods get all the keys, values, and items (key-value pairs, which are a tuple) respectively
2. "Increase":
- Assigning a new value directly to the new key means adding
3. "Delete":
del dict["key"]
, which deletes the entire key-value pairdic.clear
, will only clear the content corresponding to the key, and will not delete the key
4. The "traversing"
dictionary can traverse the elements in it through the for...in statement, the basic syntax structure:
for k,v in dt.items():
<语句块>
Note: traversing a dictionary is different from a list. The dictionary must call the items method after in, and novices often commit it for the first time.
4.5 collection set
It can be used for deduplication. Two sets can be used for intersection, difference, etc. Just understand.
4.6 Nesting of lists and dictionaries
1. List nested list
[["China", "Japan"],["Beijing", "Tokyo"]]
2. Dictionary nested dictionary
{"Asia": {"China": "Beijing", "Japan": "Tokyo"}}
3. List nested dictionary
[{"China":"Beijing"}, {"Japan":"Tokyo"}]
More common way:
{"country": ["China", "Japan"], "capital": ["Beijing", "Tokyo"]}
4.7 Summary
Is it in order | Is mutable | |
---|---|---|
list[ ] | orderly | mutable type |
tuple ( ) | orderly | immutable type |
dictionary{ } | out of order | key is immutable, value is variable |
gather{ } | out of order | mutable (not repeated) |