Introduction

Installation

Due to space limitations, please refer to online tutorials (it is recommended to use Anaconda for Python).

Code Repository

gitee

How to Run

For example, printing “Hello World”:

1
2
3
# main.py file
name = input("Please enter your name: ")
print(f"Hello, {name}!")
1
python main.py

Variable Definition and Data Types

A variable is an identifier that points to a specific address in memory, typically used to store data.
Data types represent the type of a variable, determining the amount of memory space it occupies.
Assignment involves storing data (value) at the address pointed to by the variable, allowing subsequent retrieval using
this variable.

1
2
3
4
5
6
7
# Example: Defining variables of different types
name = "Alice" # String type
age = 25 # Integer type
height = 1.68 # Float type
is_student = True # Boolean type

print(f"{name}'s age is {age}, height {height} meters, is student: {is_student}")

Arrays/Lists/Dictionaries|Maps/Sets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Define a list
fruits = ["apple", "banana", "cherry"]

# Add elements
fruits.append("orange") # Add to the end
fruits.insert(1, "grape") # Insert at index 1

# Remove elements
fruits.remove("banana") # Remove by value
del fruits[0] # Remove by index

# Modify elements
fruits[1] = "kiwi"

# Iterate through the list
for fruit in fruits:
print(fruit)

# Define a dictionary
person = {
"name": "Alice",
"age": 25,
"is_student": True
}

# Add/Modify key-value pairs
person["email"] = "alice@example.com"
person["age"] = 26

# Remove key-value pairs
del person["is_student"]

# Iterate through the dictionary
for key, value in person.items():
print(f"{key}: {value}")

# Define a set
unique_numbers = {1, 2, 3, 4, 5}

# Add elements
unique_numbers.add(6)

# Remove elements
unique_numbers.remove(3) # Error if element does not exist
unique_numbers.discard(10) # No error if element does not exist

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # Union: {1, 2, 3, 4, 5}
print(a.intersection(b)) # Intersection: {3}
print(a.difference(b)) # Difference: {1, 2}

Control Flow

Control flow defines the execution order of our program.

Sequential

Sequential execution runs from top to bottom, which is the normal execution flow of our program.

Selection

Selection executes different code based on different conditions.
The selection process is divided into single branch and multiple branches.

Single Branch

Single branch refers to having only one branch node, with only one conditional judgment.

1
2
3
4
# Example: Single branch if statement
score = 85
if score >= 60:
print("Congratulations, you passed the exam!")

Multiple Branches

Multiple branches have multiple branch nodes and multiple conditional judgments (if-elif-else | switch-case).

1
2
3
4
5
6
7
8
9
10
# Example: Multiple branch if-elif-else statement
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")

Loops

Loops represent a repeated execution process.

1
2
3
4
5
6
7
8
9
10
# Example: for loop iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# Example: while loop printing numbers 1 to 5
i = 1
while i <= 5:
print(i)
i += 1

Functions

The essence of a function is a closure with its own scope.
We can define a piece of code as a function, accepting 0 or more inputs, executing the code within the function body,
and returning 0 or more outputs at the end.
Using functions can extract common logic and simplify our code.

1
2
3
4
5
6
# Example: Define a function and call it
def greet(name):
return f"Hello, {name}!"

message = greet("Alice")
print(message)

Classes/Structs

Classes/Structs

A class is an abstract structure containing data and methods (functions). We can define it, and to use a class, we need
to instantiate it, which essentially means allocating a specified amount of space in memory to hold it.
The size of a class depends on what data is defined inside it (e.g., int), and the compiler automatically decides how
much space to allocate based on the data size.
A class can have multiple instantiated objects, meaning multiple different variables, but these variables all conform to
the structure of the class.

1
2
3
4
5
6
7
8
9
10
11
12
# Example: Define a class and create an instance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def introduce(self):
print(f"I am {self.name}, I am {self.age} years old.")

# Create an object
p1 = Person("Alice", 25)
p1.introduce()

Interfaces

Interface syntax is a way of defining behavior specifications. It describes which methods (functions) a certain type
should have, without caring about how these methods are implemented.

An interface is an abstract contract:

  • It only defines method names, parameters, and return values.
  • It does not contain any specific implementation (logic code).
  • A type is called “implementing the interface” as long as it implements all the methods defined in the interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Example: Using the abc module to simulate an interface
from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

# Calling the methods
dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!

Frameworks

To simplify development, programmers extract common logic, encapsulating it into functions or classes and methods, thus
simplifying development. During this continuous simplification process, frameworks are born.
However, in my understanding, a library (library) is a collection of extracted common methods and classes, and users can
add many different libraries as they like; while a framework (framework) is more like a set of project specifications
and templates, and then users develop based on the framework while adhering to its agreed standards or structure;
however, this boundary is often not very clear, and the two terms are frequently used interchangeably.

Web

The programs we write currently run locally. To allow users around the world to use them, we need to make them available
on the network, and web frameworks encapsulate the language’s own networking libraries and provide various methods for
offering network services.

Commonly used web frameworks in the Python language are Flask, FastAPI, Django. Here we take FastAPI as an example.

1
pip install fastapi uvicorn -i https://pypi.tuna.tsinghua.edu.cn/simple
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from fastapi import FastAPI

# Create a FastAPI instance
app = FastAPI()

# Define the root route
@app.get("/")
def read_root():
return {"message": "Welcome to the FastAPI world!"}

# Startup command: uvicorn main:app --reload
import uvicorn

if __name__ == '__main__':
# main is the filename, : app is the instance variable name
uvicorn.run(app='app:app', host="127.0.0.1", port=8080, reload=True)

Visit localhost:8080 to view. Swagger UI: http://127.0.0.1:8000/docs ReDoc: http://127.0.0.1:8000/redoc.

Databases (DB)

We currently use variables to store data, but the data in variables is placed in memory. Once the program stops, the
data in memory will be reclaimed. The next time the program starts, the operating system may allocate a different memory
space, so we need persistent storage for our data, which requires the use of database systems.

Here we take SQLAlchemy as an example:

1
pip install sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)

# 创建引擎和表
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)

# 插入数据
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Charlie", age=30))
session.commit()

# 查询数据
users = session.query(User).all()
for user in users:
print(user.name, user.age)

Expansion

  • AI Direction:

    • Data Analysis | Machine Learning | Deep Learning | Reinforcement Learning
    • numpy (Numerical Operations) | pandas (Data Loading and Processing) | matplotlib (Visualization)
    • scikit-learn (Machine Learning) | TensorFlow | PyTorch (Deep Learning)
    • Implementation of various machine learning models | Deep Learning Neural Networks
    • langchain | llama-index for Large Model Applications
  • Multithreading/Microservices/Reflection-Dynamic Proxy/File Operations/Network Programming

  • Principles of Frameworks/Handwritten Code

  • wasm/gRPC

Community

You can contact me on these platforms:


本站总访问量