Summary of python basic knowledge points

1. Summary of python basic knowledge points

Py syntax is a high-level programming language, which has become one of the most popular programming languages ​​due to its easy-to-learn and powerful features.

1.1. Variables

Variables are containers for storing data. In Py, you can define a variable with any name, but the following rules apply:

  • Variable names can only consist of letters, numbers, and underscores.
  • The first character of a variable name must be a letter or an underscore.
  • Variable names are case sensitive.

For example, the following code demonstrates how to define and use variables:

# 定义变量 x 并赋值为 10
x = 10

# 打印变量 x 的值
print(x)

# 定义变量 message 并赋值为"Hello, World!"
message = "Hello, World!"

# 打印变量 message 的值
print(message)

output result:

10
Hello, World!

1.2. Data types

In Py, common data types include integers (int), floating point numbers (float), Boolean values ​​(bool), strings (str), lists (list), tuples (tuple), dictionaries (dict), etc. The following are examples of these data types:

# 整数
x = 10
print(type(x))  # <class 'int'>

# 浮点数
y = 3.14
print(type(y))  # <class 'float'>

# 布尔值
a = True
b = False
print(type(a))  # <class 'bool'>
print(type(b))  # <class 'bool'>

# 字符串
message = "Hello, World!"
print(type(message))  # <class 'str'>

# 列表
my_list = [1, 2, 3, 4, 5]
print(type(my_list))  # <class 'list'>

# 元组
my_tuple = (1, 2, 3, 4, 5)
print(type(my_tuple))  # <class 'tuple'>

# 字典
my_dict = {
    
    'name': 'Jack', 'age': 25}
print(type(my_dict))  # <class 'dict'>

output result:

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>

1.3. Control Flow Statements

Control flow statements are used to control the flow of code execution. In Py, common control flow statements are if statements, for loops, and while loops.

1.3.1. The if statement

The if statement is used to determine which blocks of code to execute based on a condition. Here is an example:

x = 10

if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

output result:

x is greater than 5

1.3.2. for loop

The for loop is used to iterate over the elements of a sequence such as a list or tuple. Here is an example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

output result:

apple
banana
cherry

1.3.3. while loop

A while loop is used to repeatedly execute a block of code while a condition is met. Here is an example:

i = 1

while i < 6:
    print(i)
    i += 1

output result:

1
2
3
4
5

1.4. Functions

Functions are used to encapsulate some code blocks that can be reused. In Py, you can use the def keyword to define functions. Here is an example:

def square(x):
    return x ** 2

print(square(5))

output result:

25

1.5. Classes and Objects

Py is an object-oriented programming language, so it supports the concept of classes and objects. In Py, you can use the class keyword to define a class and use objects to access the properties and methods of this class. Here is an example:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def start(self):
        print("Starting the car.")

my_car = Car("Toyota", "Camry", 2021)
print(my_car.make)  # Toyota
print(my_car.model)  # Camry
print(my_car.year)  # 2021
my_car.start()  # Starting the car.

output result:

Toyota
Camry
2021
Starting the car.

1.6. Exception handling

Exception handling is used to deal with errors that may occur while the code is running. In Py, you can use try/except statements to catch and handle exceptions. Here is an example:

try:
    x = int(input("Please enter a number: "))
    print(x)
except ValueError:
    print("That was not a valid number.")

In this example, if the user enters something other than a number, a ValueError exception will be thrown, and the program will execute the code in the except block.

1.7. Modules and Packages

Modules and packages in Py are used to organize and manage code. A module is a file that contains definitions of functions, classes, etc. You can use the import keyword to introduce definitions in other modules. A package is a collection of multiple modules, which are usually stored in different folders. Here is an example:

# 在 my_module.py 文件中定义了一个 add 函数
def add(x, y):
    return x + y

# 在 main.py 文件中引入 my_module.py 文件
import my_module

print(my_module.add(5, 10))  # 15

In this example, we define an add function in the my_module.py file, and then use the import keyword in the main.py file to bring in the my_module.py file and call the add function in it.

1.8. File Operations

File operations in Py are used to read and write files. You can use the open function to open a file, and use methods such as read and write to perform read and write operations. Here is an example:

# 打开 test.txt 文件
file = open("test.txt", "w")

# 向文件中写入一行文本
file.write("Hello, World!")

# 关闭文件
file.close()

# 再次打开 test.txt 文件
file = open("test.txt", "r")

# 读取文件中的内容并打印到屏幕上
print(file.read())

# 关闭文件
file.close()

In this example, we first opened a file named test.txt using the open function, and wrote a line of text to it using write mode ("w"). Then close the file and open it again, using read mode ("r") to read this line of text from the file and print it to the screen.

1.9. Regular expressions

Regular expressions are used to match patterns in strings. In Py, you can use the re module for regular expression operations. Here is an example:

import re

# 在字符串中查找数字
text = "Hello 123 World"
result = re.search(r'\d+', text)
print(result.group(0))  # 123

In this example, we have used a regular expression with the re.search function to find the first number in the string text and print it to the screen.

1.10. Built-in functions

Many commonly used functions are built into Py, such as print, len, range, etc. The following are examples of these built-in functions:

# print 函数用于输出文本到屏幕上
print("Hello, World!")

# len 函数用于获取字符串、列表等对象的长度
my_string = "Hello, World!"
print(len(my_string))  # 13

my_list = [1, 2, 3, 4, 5]
print(len(my_list))  # 5

# range 函数用于生成一个范围内的整数序列
for i in range(1, 6):
    print(i)

# 输出结果: 
# 1
# 2
# 3
# 4
# 5

1.11. Lambda functions

A Lambda function is an anonymous function that can be created and used dynamically when needed and is often used in functional programming. Its basic syntax is: lambda arguments: expression, where arguments is a parameter list and expression is a function expression. Here is an example:

# 定义一个将两个数相加的 lambda 函数
add = lambda x, y: x + y

# 调用这个 lambda 函数
result = add(5, 10)
print(result)  # 15

In this example, we define a lambda function that adds two numbers and use it to calculate the sum of 5 and 10.

1.12. Map function

The Map function is used to apply a certain function to each element in an iterable object and return a new iterable object. Here is an example:

# 将列表中的每个元素都平方, 并返回一个新的列表
my_list = [1, 2, 3, 4, 5]
squared_list = list(map(lambda x: x**2, my_list))
print(squared_list)  # [1, 4, 9, 16, 25]

In this example, we have applied the lambda function to each element in my_list using the map function, squared it, and returned a new list.

1.13. Filter function

The Filter function is used to filter each element in an iterable object and return a new iterable object with eligible elements. Here is an example:

# 从列表中过滤出所有的偶数, 并返回一个新的列表
my_list = [1, 2, 3, 4, 5]
filtered_list = list(filter(lambda x: x % 2 == 0, my_list))
print(filtered_list)  # [2, 4]

In this example, we use the filter function to filter each element in my_list, leaving only the even numbers in it, and return a new list.

1.14. Decorator decorator

Decorator decorators are used to enhance the functionality of existing functions without modifying their code. Its basic syntax is: @decorator, followed by the function to be defined, where decorator is a decorator function. Here is an example:

# 定义一个装饰器函数, 用于计算函数执行时间
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print("Time taken: ", end_time - start_time)
        return result
    return wrapper

# 使用这个装饰器装饰一个函数
@timer
def my_function():
    time.sleep(2)
    print("Function executed.")

# 调用被装饰的函数
my_function()

In this example, we define a decorator function timer that can time the execution time of the decorated function. Then we decorate the my_function function with the @timer syntax to make it support the function of calculating the execution time. Finally we call the decorated my_function function and observe the result.

1.15. Iterators and Generators

Iterators and generators in Py are used to handle situations such as large data collections or infinite sequences. An iterator is an object that supports returning elements one by one while traversing. Whereas a generator is a special kind of iterator that can dynamically generate elements when needed. Here is an example:

# 定义一个简单的迭代器类, 用于遍历一个列表
class MyIterator:
    def __init__(self, my_list):
        self.index = 0
        self.my_list = my_list

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.my_list):
            result = self.my_list[self.index]
            self.index += 1
            return result
        else:
            raise StopIteration

# 使用这个迭代器来遍历一个列表
my_list = [1, 2, 3, 4, 5]
my_iterator = MyIterator(my_list)
for item in my_iterator:
    print(item)

# 定义一个简单的生成器函数, 用于生成一个斐波那契数列
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# 使用这个生成器来生成一个斐波那契数列
fib = fibonacci()
for i in range(10):
    print(next(fib))

In this example, we define a simple iterator class MyIterator that can iterate over a list. Then we use this iterator to traverse the list my_list and print the elements.

Additionally, we define a simple generator function fibonacci that generates an infinite sequence of Fibonacci numbers. We then use this generator to generate a Fibonacci sequence of length 10.

1.16. Multithreading and multiprocessing

Multithreading and multiprocessing in Py are used to run multiple tasks at the same time to improve the performance of the program. Multithreading is running multiple threads simultaneously within the same process while multiprocessing is starting multiple processes and distributing tasks among them. Here is an example:

# 使用多线程处理一些任务
import threading

def task1():
    print("Task 1 executed.")

def task2():
    print("Task 2 executed.")

# 同时运行两个线程
thread1 = threading.Thread(target=task1)
thread2 = threading.Thread(target=task2)
thread1.start()
thread2.start()

# 使用多进程处理一些任务
import multiprocessing

def task3():
    print("Task 3 executed.")

def task4():
    print("Task 4 executed.")

# 同时启动两个进程
process1 = multiprocessing.Process(target=task3)
process2 = multiprocessing.Process(target=task4)
process1.start()
process2.start()

In this example, we use multithreading and multiprocessing to handle some tasks concurrently. For multithreading, we created two threads using the threading module and distributed tasks between them. And for multiprocessing, we use the multiprocessing module to start two processes and distribute the tasks between them.

Note that when using multi-threading and multi-process in Py, you need to pay attention to issues such as thread safety and inter-process communication to avoid problems such as deadlocks and race conditions.

1.17. Exception handling

The exception handling mechanism in Py is used to deal with errors or abnormal conditions that occur when the program is running, so as to avoid program crashes or produce unpredictable results. Exception handling uses the try-except structure to catch exceptions and execute related processing logic. Here is an example:

# 使用异常处理机制处理程序中的错误
try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

# 使用多个 except 块来处理不同类型的异常
try:
    my_list = [1, 2, 3]
    print(my_list[3])
except IndexError:
    print("Index out of range.")
except ValueError:
    print("Invalid value.")
except:
    print("Some other error occurred.")

In this example, we use the try-except construct to catch errors in the program. In the first try statement we try to divide by 0, which raises a ZeroDivisionError exception, so we use the except statement to catch this exception and print an error message.

And in the second try statement we try to access the 4th element in the list my_list, which raises an IndexError exception, so we use an except block to catch this exception and print an error message. In addition, we also added a ValueError and a generic except block for handling other types of exceptions, respectively.

1.18. with statement

The with statement in Py is used to manage the opening and closing of some resources (such as files) to avoid leaks or errors caused by forgetting to close resources. Objects used in a with statement must have __enter__() and __exit__() methods. Here is an example:

# 使用 with 语句自动管理文件资源
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

In this example, we use the with statement to automatically manage file resources. When the program leaves the with code block, the file is automatically closed without manually calling the close() method.

1.19. Python standard library and third-party libraries

Py contains a large number of standard libraries, which provide a wealth of functions and tools that can help us write code more easily. In addition, there are many third-party libraries that can extend the functionality of Py, such as NumPy, Pandas, and Django, etc. Here is an example:

# 使用标准库中的 random 模块和 datetime 模块
import random
import datetime

# 生成一个长度为 10 的随机数列表
my_list = [random.randint(1, 100) for _ in range(10)]
print(my_list)

# 获取当前时间并格式化输出
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

In this example, we have used the random module and the datetime module from the standard library. Among them, the random module is used to generate random numbers, and the datetime module is used to obtain the current time and format the output.

1.20. Application fields of Py

Py can be applied in various fields such as web development, data science, artificial intelligence, natural language processing, game development, etc. Here are some examples:

  • Web Development: Use frameworks such as Django or Flask for web application development.
  • Data Science: Data analysis and visualization using libraries such as NumPy, Pandas, and Matplotlib.
  • Artificial Intelligence: Use libraries like TensorFlow and PyTorch for tasks like machine learning and deep learning.
  • Natural Language Processing: Text analysis and processing using libraries such as NLTK and SpaCy.
  • Game Development: Use tools such as Pygame to develop 2D games.

In summary, Py is a powerful, easy-to-learn and use programming language that can be used for application development in many fields.

Guess you like

Origin blog.csdn.net/wan212000/article/details/131669252