Python learning - basic introduction

Introduction to Basic Python Syntax

variable

Variables in Python do not need to be declared, they can be assigned directly. The type of the variable is automatically determined from the assignment.

a = 1
b = "hello"
c = True

type of data

Data types in Python:

  • int integer
  • float float type
  • str string
  • bool Boolean type
  • list list
  • tuple tuple
  • dictionary dictionary
  • set collection

There is also the array-like array type introduced through the numpy library.
The type will be automatically inferred based on the initial value without manual declaration. Otherwise, if there is no initial value, manual declaration is required.

num = 1  # 整型
_num: int = 1  # 以上等同
type(num) # 获取数据类型
flo = 1.0  # 浮点型
_flo: float = 1.0  # 以上等同
str = "hello"  # 字符串
_str: str = "hello"  # 以上等同
is_true = True  # 布尔型
_is_true: bool = True  # 以上等同
the_tuple = (1, 2, 3)  # 元组,与列表的区别在于元组是只读类型,长度固定,元素不可修改,常用于函数多返回值和将静态资源缓存在内存中使用
_the_tuple: tuple[int, ...] = (1, 2, 3)  # 以上等同
the_dictionary = {
    
    "name": "Tom", "age": 18}  # 字典
_the_dictionary: dictionary = {
    
    "name": "Tom", "age": 18}  # 以上等同

list list

A list is not an array. Each item in the list can be a different type of value, while an array has all the same items and needs to be imported into the library before it can be used.

Add to

Add 3 to the end:

list = [1]
list.append(3)

Add an iterable object to the end, which is convenient for adding multiple elements at once:

list = [1]
list.extend([4, False])

Insert the string element "10" at index 1:

list = [1, 2, 3]
list.insert(1, "10")

delete

Remove the specified string element "10" from the list:

list = [1, "10", 2, 3]
del list["10"]

Delete the element at the specified index 1 from the list. If no index value is specified, the last element will be deleted by default:

list = [1, 2, 3]
list.pop(1)

Remove the first occurrence of element 3 from the list:

list = [1, 2, 3, 3]
list.remove(3)

Statistical Analysis

Return the length of the list:

list = [1, 2, 3]
len(list)

Count the occurrences of element 3:

list = [1, 2, 3, 3]
list.count(3)

The following numeric lists are available:

list = [1, 2, 3, 3]
min(list) # 求最小值
max(list) # 求最大值
sum(list) # 求和

slicer

The slicer syntax is convenient for indexing and counting lists/tuples/arrays to return a new sliced ​​list.
The syntax is list[startindex:endindex:sort]that you can just add a colon without filling in a specific value.
Multi-dimensional uses commas to separate list[r_startindex,c_startindex:r_endindex,c_endindex:sort]
rows and columns Returns a list of elements starting from index 1 to 3 (the header does not include the end, the element at index 1 will be included in the slice, and the element at index 3 will not be put into the slice):

list = [1, 2, 3, 5, 7, 10, 30]
sub_list = list[1:3]

Return a list slice with the last three elements:

list = [1, 2, 3, 5, 7, 10, 30]
sub_list_last = list[-3:]

Return a slice that reverses the entire list:

list = [1, 2, 3, 5, 7, 10, 30]
sub_list_reverse = list[::-1]

set collection

The set collection represents a collection of variables that cannot be repeated, for example, two 1s cannot be stored at the same time, but the collection is not necessarily ordered.

the_set = {
    
    "joker", "king", "queen"} # set 无重复集合
_the_set: set = {
    
    "joker", "king", "queen"} # 以上等同

Add to

Add new data, which can be a single element or a tuple

the_set = {
    
    }
the_set.add("kiva")

Add a set of data, which can be tuples, lists, dictionaries, etc. If you add a string, it will be automatically split into multiple individual characters

the_set = {
    
    }
list1 = [1, 2, 3]
the_set.update(list1)

judge whether there is

if "king" in the_set:
    print("it's in.")

delete

Delete the data, and report an error if the data does not exist

the_set = {
    
    }
the_set.remove("joker")

Delete data, but do not report an error even if the data does not exist

the_set = {
    
    }
the_set.discard("joker")

delete the last added data

the_set = {
    
    "joker", "queen"}
the_set.add("king")
the_set.pop()

clear data

the_set = {
    
    "joker", "queen", "king"}
the_set.clear()

array array

Python itself does not have an array type, so it needs to use the third-party library numpy. Learning python is generally used for artificial intelligence data analysis, and data analysis requires the use of many methods in the numpy library.
Among them, the array method is very similar to the arrays used in other development languages. It also supports index index, index value index_key, multi-dimensional features, and can also be converted with list lists, tuple tuples, and diconary dictionaries, etc.

import numpy as np

list = [4, 5, 6]
arr = np.array(list) # 列表转数组
list2 = arr.tolist() # 数组转列表
arr.append(3)  # 采用append添加新数据
arr.count(3)  # 获取元素3出现的次数
arr.extend([4, 5])  # 添加可迭代对象到数组
arr.index(2)  # 获取元素2所在的首个索引
arr.insert(1, 10)  # 插入元素10到索引1位置
arr.pop(1)  # 删除指定索引的元素
arr.remove(3)  # 删除首个出现的指定元素
arr.reverse()  # 反转数组

operator

Common operators in Python include arithmetic operators, comparison operators, logical operators, etc.

a = 1 + 2  # 加法运算
b = 3 - 2  # 减法运算
c = 2 * 3  # 乘法运算
d = 4 / 2  # 除法运算
e = 5 % 2  # 取模运算
f = 2 ** 3  # 幂运算
g = 3 > 2  # 大于运算
h = 3 == 2  # 等于运算
i = not True  # 非运算
j = True and False  # 与运算
k = True or False  # 或运算

control statement

Common control statements in Python include if statement, for loop, while loop, etc.

if/else

# if语句
if a > b:
    print("a > b")
elif a == b:
    print("a == b")
else:
    print("a < b")

for loop

e = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in e:
    print(i)

Note that the internal block cannot directly modify the value of the external block variable, because it will be regarded as defining a new value

a = 1
for i in range(10):
    a = a + i
print(a)

Here a is still equal to 1, because a in the for loop will be regarded as a redeclared internal variable, and a+i is always assigned to the internal variable a, not the external variable a.
The solution is to use class attributes or self-add operations:

a = 1
for i in range(10):

while

condition = True
while condition:
# do something

Python uses the def keyword to define functions, which can accept parameters and return values.

def add(a, b):
    return a + b


result = add(1, 2)
print(result)

kind

The class keyword is used to define a class, which can contain unique attributes and methods, and generate different instances for use according to parameters.
Among them, the class constructor is defined with the specified method name __init__, the member method is defined directly, and the static method needs to be declared with the decorator staticmethod

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


    def say_hello(self):
        print("Hello, my name is", self.name)


    @staticmethod
    def print():
        print("hello, this is class Person.")


p = Person("Tom", 18)
Person.print()
p.say_hello()

exception handling

Python can use the try...except...finally statement to handle exceptions.

try:
# do something
except Exception as e:
# handle exception
finally:
# do something finally

file operation

In Python, the open function can be used to open the file, and the with statement can be used to perform file operations in the internal block, which can automatically close the file.

with open("file.txt", "r") as f:
    content = f.read()
    print(content)

module

In Python, you can use the import statement to import the module, or you can use the from...import statement to import the specified content in the module.

import math
from cmd import Cmd

result = math.sqrt(2)
print(result)

from datetime import datetime

now = datetime.now()
print(now)
cmd = Cmd(now)

remaining parameters/parameter tuple/parameter dictionary

Use asterisk plus variable name *args and double asterisk plus variable name **kwargs to create positional parameter tuples and keyword parameter dictionaries

# 此处的星号*表示将所有参数收入args作为元组
def sayhello(*args):
    # 可以不展开直接使用,类型将是元组,参数数量只有一位
    print(args)
    # 此处的星号*表示将所有参数展开填入作为实参,参数数量根据实际而定,
    print(*args)


# 此处的双星号**表示将所有参数收入kwargs作为字典,带有变量名和变量值
def saybai(**kwargs):
    for key in kwargs:
        print(key, kwargs[key])


def main():
    list = ["mimi", "jiji", "kuuga", "mandala"]
    sayhello(*list)
    sayhello("mimi", "jiji", "kuuga", "mandala")
    saybai(mimi="再见", jiji="See you", kunga="Sa yo na la", mandala="hen")

decorator

The use of decorators, like most development languages, is a parasitic way to try to take over the state of the object (class, function) being decorated.

def decorater(func):
    print("define decorate!!!")

    def wrap(*args):
        print("prev decorating!!!")
        result = func(*args)
        print("next decorating:" + result)
        return result

    return wrap


@decorater
def handler(a, b) -> int:
    return a * 2 + b

Use Python for data analysis

Reference source:

Guess you like

Origin blog.csdn.net/u013102711/article/details/130553771
Recommended