python: basics

environment:

  • window11
  • python 3.10.6
  • vscode
  • javascript, c/c++/java/c# basics (compared with these languages)

Reference: https://www.bilibili.com/video/BV1qW4y1a7fU/

note

insert image description here

1. Data type

The basic six data types can be used type()to view , as shown in the figure below:

insert image description here

1.1 Numbers

support

  • integer (int)
  • floating point number (float)
  • Complex numbers (complex), such as: 4+3j, end with j to indicate complex numbers
  • Boolean (bool) True is represented by 1, False is represented by 0, conversely, 1 represents True, and others represent False

1.2 String (String)

Can be declared with single or double quotes, or triple single or double quotes

1.3 List (List)

ordered mutable list

1.4 Tuples

An ordered immutable sequence, which can record a bunch of immutable Python data sets in an orderly manner

1.5 Collection (Set)

Unordered and non-repeated combination
can record a bunch of non-repeated Python data sets in disorder

1.6 Dictionary

Unordered Key-Value Collection
A bunch of Key-Value type Python data collections can be recorded out of order

1.7 Data type conversion

Any type can be converted to a string, such as: number/string/list/tuple/collection/dictionary => string, as shown below:
insert image description here

But the string cannot be converted to any other type, because the essence of the string is a list of characters, let's see the conversion effect:
insert image description here

For other conversions, such as: int <=>float, you need to pay attention: the conversion of float to int will cause precision loss (note that the precision is lost, not rounded), see the figure below:
insert image description here

2. Variables

Python is a scripting language with weak typing, so a variable can be assigned other values ​​at will, or even change the data type, which is javascriptsimilar to Python.
In addition, there is no need to define variables in python, just use them directly, as follows:
insert image description here

3. Operators

Common operators: +addition, -subtraction, multiplication, division, *integer division, remainder, exponent///%**

Here are a few key ones to focus on:
insert image description here

4. String extension

4.1 Three methods of definition:

  • use single quotes' abc'
  • use double quotes"abc"
  • use """abc"""or'''abc'''

Summary of features:

  1. Single quotes and double quotes have similar functions. Supporting these two methods gives us the possibility of not writing transfer characters \, such as:
    insert image description here
  2. Using """abc"""or '''abc'''can save us \the trouble of expressing line breaks. See the comparison effect below:
    insert image description here
    In addition, we need to pay attention, """abc"""if you don’t want to have a line break at the beginning and end '''abc'''of and , you should write it closely, otherwise a line break will be generated, as follows:
    insert image description here

4.2 String concatenation

Use +can be spliced, but unlike other languages, we cannot add strings and other types (such as: int), as follows:
insert image description here

JavaScript is allowed, so please note:
insert image description here

4.3 String Formatting

The above-mentioned +simple concatenation of strings is okay, but it is not easy to read when adding a lot of content, and it does not support other data types (such as: int/float) to automatically convert strings, so there are the following two strings Formatting method:

  • %d, %f, %s: similar to c language
  • f"{exp}{exp2}"

Here is the effect:
insert image description here

5. Interactive input

You can use to input(prompt)obtain the input from the user console. After pressing Enter, the user input 字符串will be passed to the program, as follows:
insert image description here

Six, for loop and range

The for loop in python does not have for(int x=0;x<10;x++)this format, only: for x in li:this, as follows: In
insert image description here
this way, there is no way to get the current progress in the loop body, but we can userange

rangeThe function itself is to generate a range, the format is: range(start,end,step)Note: start is included, end is not included, see the example below:
insert image description here
Then, the combination rangeand forcycle are as follows:
insert image description here

Seven, function

7.1 Simple functions

Look directly at the usage example below:
insert image description here
the returned value Nonecan be used ifin judgment, False
returnand the representation return Noneis the same as .

7.2 Parameters and return values ​​in functions

In addition, functions in python also have some features, such as:

  • Support for returning multiple values
  • Support default parameters, keyword parameters, variable length parameters (* and **)

Look directly at the example:
insert image description here

Examples of variable length parameters:
insert image description here

7.3 Functions as parameters/anonymous functions/lambda functions

insert image description here

8. List of containers

8.1 Concept and operation

The list in python is similar to javascriptthe array in, and c#the list in, the common operations are as follows:

  • Get list length:len(li)
  • Get the specified index element:li[index]
  • traverse:for x in li:
  • Get the index of the value:li.index(ele)
  • insert:li.insert(index,ele)
  • addition:li.apped(ele)
  • Append another container:li.extend(li2)
  • Remove specified elements:li.remove(ele)
  • Remove by subscript:dele li[index]
  • pop from the end:delEle=li.pop()
  • clear the list:li.clear()
  • Count the number of elements in a list:li.count(ele)
  • Sort the list:li.sort(key=lambda: x: x"age"], reverse=True)

See the example below:

8.2 Accessing Lists by Subscript

insert image description here

8.3 Looping through lists

insert image description here

8.4 Common function usage (addition, deletion, modification, sorting, statistics)

# 插入到指定位置
print()
print("------li.insert()-------")
li = ["刘备", "关羽", "张飞"]
li.insert(0, '曹操')
print(f'["刘备", "关羽", "张飞"].insert(0,"曹操")=> {
      
      li}')

# 追加元素
print()
print("--------append()------")
li = ["刘备", "关羽", "张飞"]
li.append("孔明")
print(f'["刘备", "关羽", "张飞"].append("孔明")=> {
      
      li}')

# 追加另一个容器
print()
print("--------extend()------")
li = ["刘备", "关羽", "张飞"]
li.extend(["孙策", "孙权"])
print(f'["刘备", "关羽", "张飞"].append(["孙策", "孙权"])=> {
      
      li}')

# 移除指定元素
print()
print("--------remove(): 只移除第一个------")
li = ["刘备", "关羽", "张飞", "关羽"]
li.remove('关羽')
print(f'["刘备", "关羽", "张飞","关羽"].remove("关羽")=> {
      
      li}')

# 根据下标移除
print()
print("--------del list[index]: 根据下标移除------")
li = ["刘备", "关羽", "张飞"]
del li[1]
print(f'["刘备", "关羽", "张飞"] del li[1]=> {
      
      li}')

# 从末尾移除一个
print()
print("--------pop(): 从末尾弹出一个------")
li = ["刘备", "关羽", "张飞"]
ele = li.pop()
print(f'["刘备", "关羽", "张飞"].pop()=> {
      
      li}, ele={
      
      ele}')

# 清空列表
print()
print("--------clear(): 清空列表------")
li = ["刘备", "关羽", "张飞"]
li.clear()
print(f'["刘备", "关羽", "张飞"].clear()=> {
      
      li}')

# 获取列表长度
print()
print("--------len(li): 获取列表长度------")
li = ["刘备", "关羽", "张飞"]
count = len(li)
print(f'len(["刘备", "关羽", "张飞"])=> {
      
      count}')

# 统计列表元素数量
print()
print("--------count(ele): 统计列表某个元素数量------")
li = ["刘备", "关羽", "张飞", "关羽"]
count = li.count("关羽")
print(f'["刘备", "关羽", "张飞","关羽"].count("关羽")=> {
      
      count}')

# 列表排序
print()
print("--------sort(): 列表排序------")
li = ["a", "c", "b"]
li.sort()
print(f'["a","c","b"].sort()=> {
      
      li}')
li = ["a", "c", "b"]
li.sort(reverse=True)
print(f'["a","c","b"].sort(reverse=True)=> {
      
      li}')
li = [{
    
    "name": "小明", "age": 18},
      {
    
    "name": "小花", "age": 16},
      {
    
    "name": "小刚", "age": 20}]
li.sort(key=lambda x: x["age"], reverse=True)
print(f'[dict1,dict2,dict3].sort(key=lambda x: x["age"])=> {
      
      li}')

""" 输出如下:
PS D:\jackletter\pylearn> py .\15.py

------li.insert()-------
["刘备", "关羽", "张飞"].insert(0,"曹操")=> ['曹操', '刘备', '关羽', '张飞']

--------append()------
["刘备", "关羽", "张飞"].append("孔明")=> ['刘备', '关羽', '张飞', '孔明']

--------extend()------
["刘备", "关羽", "张飞"].append(["孙策", "孙权"])=> ['刘备', '关羽', '张飞', '孙策', '孙权']

--------remove(): 只移除第一个------
["刘备", "关羽", "张飞","关羽"].remove("关羽")=> ['刘备', '张飞', '关羽']

--------del list[index]: 根据下标移除------
["刘备", "关羽", "张飞"] del li[1]=> ['刘备', '张飞']

--------pop(): 从末尾弹出一个------
["刘备", "关羽", "张飞"].pop()=> ['刘备', '关羽'], ele=张飞

--------clear(): 清空列表------
["刘备", "关羽", "张飞"].clear()=> []

--------len(li): 获取列表长度------
len(["刘备", "关羽", "张飞"])=> 3

--------count(ele): 统计列表某个元素数量------
["刘备", "关羽", "张飞","关羽"].count("关羽")=> 2

--------sort(): 列表排序------
["a","c","b"].sort()=> ['a', 'b', 'c']
["a","c","b"].sort(reverse=True)=> ['c', 'b', 'a']
[dict1,dict2,dict3].sort(key=lambda x: x["age"])=> [{'name': '小刚', 'age': 20}, {'name': '小明', 'age': 18}, {'name': '小花', 'age': 16}]
PS D:\jackletter\pylearn>
"""

8.5 Adding lists

There is another function that we may not have thought of, that is, two lists can be added, as follows:
insert image description here
But we can only use it +, and an error -will be reported when using . . .

Nine, the tuple of the container

In python , tuples are read-only, so there are no operations such as adding, deleting, and modifying list. Just look below:tuple

9.1 Definition of tuple

insert image description here

9.2 Tuple access and traversal

Because tuples are stored in order, they support index access and support for loops, as follows:
insert image description here

9.3 Tuple functions index and count

This is similar to the usage of list, as follows:
insert image description here

Ten, the string of the container

A string can be seen as a read-only container of characters, similar tolist

10.1 Subscript access and traversal of strings

insert image description here

10.1 Common functions

insert image description here

11. Slicing of containers (sequences)

List (list), tuple (tuple), and string (str) are all sequences, and they support slice operations.
The syntax of slicing is: seq[start:end:step], where the default values ​​of start/end/step are:0/len(seq)/1

Let's take a list as an example to see its effect: insert image description here
the same is true for tuples and strings, as follows:
insert image description here

12. A Collection of Containers

Compared with lists, tuples, and strings, collections are characterized by being unordered and unique.
Because unordered naturally cannot be accessed with subscripts, nor can it be used for slicing.
The only thing is that the collection is automatically deduplicated.

12.1 Definition of Set

insert image description here

12.2 Collection traversal

insert image description here

12.3 Common operations on collections

  • Add tose.add(ele)
  • remove/eject se.remove(ele)/ele = se.pop()
  • emptyse.clear()

As shown below:
insert image description here

There are also set operations

  • find intersectionse & se2
  • Unionse | se2
  • difference setse - se2
  • complement setse ^ se2

As shown below:
insert image description here

There is also a collection operation that overwrites the result of the first collection, such as:
se.intersection_update(se2)
se.difference_update(se2)

no more experiments

13. Dictionary of Containers

The dictionary and object in python javascripthave the same meaning, just look at the following example:

Dictionary definition:
insert image description here

Note: We will report an error dic[key]if does not exist, but we can use it dic.get(key), of course we can also use it __contains__to judge, as follows:
insert image description here

Dictionary traversal:
insert image description here
dictionary change data:
insert image description here

14. File Operation

File mode:
rread-only
w: overwrite if it exists, create if it does not exist
a: append if it exists, create and append if it does not exist

Simple writing and reading and writing examples:
insert image description here
we can also specify the number of characters to read (note: not the number of bytes) or read a line, as follows (still use the txt created above):
insert image description here
we can also use the for loop to read, In addition, we can use withthe keyword to prevent forgetting to write close()
insert image description here

15. Abnormal

Just look at the example below:

print("------捕获异常---")
try:
    i = 5/0
except Exception as ex:
    print(type(ex), ex)

print()
print("------捕获异常---")
try:
    dic = {
    
    "age": 18}
    i = dic["name"]
except Exception as ex:
    print(type(ex), ex)

print()
print("------捕获异常---")
try:
    i = 5/0
except:
    print("异常了")

print()
print("-------捕获多种异常--------")
try:
    i = 5/0
except (KeyError, ZeroDivisionError) as ex:
    print(type(ex), ex)

print()
print("------finally-------")
try:
    i = 5/0
except:
    print("异常了")
finally:
    print("finally执行了")

print()
print("--------自己引发异常-------")
try:
    raise Exception("测试手动抛异常")
except Exception as ex:
    print(ex)

The output is as follows:

insert image description here

16. Modules and Packages

Concept: Simple to understand in python, a file is a module
Syntax for importing modules:
[from 模块名] import [ 模块 | 类 | 变量 | 函数 | * ] [as 别名]

Common forms:

  • import 模块名
  • from 模块名 import 类、变量、方法等
  • from 模块名 import *
  • import 模块名 as 别名
  • from 模块名 import 功能名 as 别名

See a simple example (provided by the import system):
insert image description here

16.1 Custom modules

We can customize the module and then import it as follows:

# 路径: /cc/c_28.py

# 默认定义的都可以被导出, 可以使用 __all__指定仅导出哪些,但仅限定在 import *
__all__ = ["funcSub"]

def funcSub(x, y):
    return x-y
    
print()
print("-------------")
print(f"__file__:{
      
      __file__}")
print(f"__name__:{
      
      __name__}")
if (__name__ == "__main__"):
    print(f"直接运行脚本: {
      
      __file__}")
else:
    print(f"导入了脚本: {
      
      __file__}")
# 路径: /pp/test.py
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from cc.c_28 import funcSub

print()
print("-----------")
print(f"funcSub(1, 2)=>{
      
      funcSub(1, 2)}")

Run as follows:
insert image description here

There are a few points to note above:

  • __name__Can be used to determine whether the current module is imported or run directly
  • __all__It can be used to restrict the import (import *) to only import the specified module (note that it is only valid when import *)
  • The specified path can be added to the module search sys.path.append(xx)using

16.2 Packages and custom packages

In python, a package is actually a folder in which many modules (code files) can be placed and classified by package for easy management.
However, there is a difference between a python package and a normal folder: there is a __init__.pyfile to identify that it is a package, and ` all`` is usually used in this file to limit the exported content.
like:
insert image description here

Seventeen, pip and domestic sources

Reference: "Python Configure Domestic Mirror Source Operation Steps"

Similar to the ones in java , maventhere are also programs for managing packages. We can conveniently refer to the three-party package through it, as follows:javascriptnpmpythonpip

We can first view the configuration through the command:
insert image description here
to explain:

  • pip config listDisplay all configurations, the domestic source has been set up currently, if not, you can refer to:
    pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
    pip config set install.trusted-host pypi.tuna.tsinghua.edu.cn

    Other commonly used sources are:
    1. South China University of Technology mirror source
    http://pypi.hustunique.com/simple/%29
    2. Tsinghua University
    https://pypi.tuna.tsinghua.edu.cn/simple
    3. Douban
    http://pypi.douban.com/simple/
    4. Tsinghua University Open Source Mirror Station
    https://mirrors.tuna.tsinghua.edu.cn/
    5. NetEase Open Source
    http://mirrors.163.com/
    6. Huawei
    https://mirrors.huaweicloud.com/
    7. Alibaba
    https://opsx.alibaba.com/mirror/

  • pip listDisplay the currently installed three-party packages
    As you can see, I have installed one currently numpy, and the other two are self-contained. The installation command is:
    pip install aliyun-python-sdk-core==2.13.36(you can also not specify the version)
    as follows:
    insert image description here

18. Virtual environment

18.1 Concept

pythonAnd java, c#this language is not the same as:

  • javaand c#are both static languages. They install packages compiled by others. They can cache each version of a package and then add it to the project reference;
  • It ispython an interpreted language, and the installation is all source code. There is no 将包的某个版本加入到项目引用such statement, so it is a lot of trouble to manage;

javascriptIt is also an interpreted language, and it has the same problem, but npmit puts all the packages referenced by this project under node_moudulesthe folder. The disadvantage is that every new project has to be re-downloaded, even if we use the same version of the xxxx package.

pythonIn order to solve this problem, the concept of a virtual environment is proposed, which is to make pythona copy as a new environment, so that our installation package in the new environment will not affect other environments, and isolation is achieved. for example:

  • We imported version 1.0 of the xxxx package in environment A, and imported version 2.0 of the xxxx package in environment B. They do not affect each other;
  • Project A and Project B use environment A because they both import the same version of the package, and project C and project D use environment B because they also use the same environment package;

18.2 Creating and using virtual environments

We first select a directory, such as D:\jackletter\my-venv, and then execute as follows:py -m venv my-venv

insert image description here
After the execution is complete, look inside:
insert image description here
we need to activate this environment, as follows:
.\Scripts\Activate.ps1
insert image description here
In fact, activation is to my-venvconfigure the path to the path, as follows:
insert image description here
In the virtual environment, the packages we install are all my-venv\Lib\site-packagesunder , as follows:
insert image description here

The command to exit the virtual environment is: .\Scripts\deactivate.bat, but it is not easy to use in powershell. . . But it is possible in cmd. . .

18.3 requirements.txt

requirements.txt can record the package version that the current project depends on. The dependency function in package.json is the same. The format is as follows:
insert image description here

If this file already exists in a project directory, you can use pip install -r requirements.txtone click to install the dependencies in it.
If not, it can be generated with all packages and versions of the current environment:pip freeze > requirements.txt

Guess you like

Origin blog.csdn.net/u010476739/article/details/126575368