Introduction to Python Programming - Analyze eight core knowledge points to quickly master Python programming

Preface

Python is a relatively easy programming language to learn and use. For developers with other programming experience (such as C++), learning Python may be easier and faster. Python language features:

  1. Concise syntax: Python’s syntax is relatively simple and easy to read and write. Compared with C++, Python has fewer lines of code, more direct expression, and does not require excessive syntax and symbols.

  2. Dynamic type system: Python is a dynamically typed language that does not require explicit declaration of variable types. This makes writing code more flexible and reduces type-related complexity.

  3. Rich standard library: Python has a rich standard library and third-party libraries, providing a large number of modules and tools that can help solve various problems. These libraries are very helpful for completing tasks and developing quickly.

  4. Wide application fields: Python is used in many fields, including web development, data science, artificial intelligence, natural language processing, etc. This allows people who learn Python to find uses in different fields.

  5. Strong community support: Python has a large and active developer community, with a large number of tutorials, documentation, blogs and community resources for learning and reference.

  6. Ease of use and flexibility: Python is easy to use and flexible, supports multiple programming paradigms (object-oriented, functional programming, etc.), and is suitable for rapid Prototype development.

1. Basic grammar

Common basic operations in Python. The definition and use of variables, data type operations, conditional statements and loop structures are the basis of Python programming.

1. Definition and use of variables

# 定义变量并赋值
name = "Alice"
age = 30

# 使用变量
print("Name:", name)
print("Age:", age)

2. Data type operations

# 整数操作
num1 = 10
num2 = 5
result = num1 + num2
print("Result:", result)

# 字符串操作
str1 = "Hello, "
str2 = "world!"
combined_str = str1 + str2
print("Combined String:", combined_str)

3. Conditional statement

# 条件语句示例
score = 85
if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
else:
    print("及格")

4. Loop structure

# for循环示例
for i in range(1, 6):
    print(i)

2. Functions and modules

1. Definition and calling of functions

# 定义函数
def greet(name):
    return "Hello, " + name + "!"

# 调用函数
result = greet("Alice")
print(result)

2. Parameter passing

# 函数参数传递
def add_numbers(a, b):
    return a + b

# 调用函数并传递参数
sum_result = add_numbers(5, 3)
print("Sum:", sum_result)

3. Create and use modules

When creating and using modules, you can organize functions or code into separate Python files and import and use it in other Python files.

Module file (for example, example_module.py):
# example_module.py

def multiply_numbers(x, y):
    return x * y
Using modules in the main file:
# 主文件

# 导入模块
import example_module

# 使用模块中的函数
result = example_module.multiply_numbers(4, 5)
print("Multiplication Result:", result)

These examples show the definition and calling of functions in Python, parameter passing, and how to create and use modules. Functions can encapsulate code for multiple use, while modules can organize related functions into separate files for easy reuse and maintenance.

3. Object-oriented programming

1. Class definition and object creation

# 类的定义
class Animal:
    def __init__(self, species, sound):
        self.species = species
        self.sound = sound

    def make_sound(self):
        print(f"A {
      
      self.species} makes a {
      
      self.sound} sound")

# 创建对象实例
dog = Animal("dog", "bark")
cat = Animal("cat", "meow")

# 调用对象的方法
dog.make_sound()
cat.make_sound()

2. Inheritance

# 继承示例
class Dog(Animal):
    def wag_tail(self):
        print("The dog wags its tail")

# 创建派生类对象
golden_retriever = Dog("dog", "bark")

# 调用继承的方法
golden_retriever.make_sound()
golden_retriever.wag_tail()

3. Polymorphism

# 多态示例
def make_animal_sound(animal):
    animal.make_sound()

# 不同对象调用相同方法
make_animal_sound(dog)
make_animal_sound(cat)
make_animal_sound(golden_retriever)

Classes allow the creation of object models, inheritance allows new classes to be created and reuse functionality of existing classes, and polymorphism allows different objects to respond differently to the same methods.

4. File operations

File reading and writing operations in Python usually use the built-inopen() functions.

###1. Read files

# 打开文件进行读取(默认为只读模式)
with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

The above code will open a file named file.txt, read the file contents using the read() function, and then print the contents.

2. Write to file

# 打开文件进行写入(若不存在则创建文件,存在则覆盖内容)
with open('file.txt', 'w') as file:
    file.write("Hello, this is a sample text!\n")
    file.write("Writing to a file in Python is easy.")

When using file read and write operations, ensure you have appropriate access rights to the file path and handle file opening and closing operations carefully to avoid the possibility of resource leaks or file corruption.

5. Exception handling

In Python, you can use try-except blocks to catch and handle exceptions. This mechanism enables graceful handling of possible errors.

1. Catching and handling exceptions

try:
    # 尝试执行可能引发异常的代码
    result = 10 / 0  # 除以零会引发ZeroDivisionError异常
except ZeroDivisionError:
    # 捕获ZeroDivisionError异常并处理
    print("Error: Division by zero!")

tryThe block contains code that may cause an exception. When an ZeroDivisionError exception occurs, the except block will capture the exception and output error information.

2. Handle different types of exceptions

try:
    # 尝试执行可能引发异常的代码
    value = int(input("Enter a number: "))
    result = 10 / value
except ZeroDivisionError:
    # 处理除以零异常
    print("Error: Division by zero!")
except ValueError:
    # 处理输入非数字的异常
    print("Error: Invalid input. Please enter a number.")

In addition to catchingZeroDivisionError exceptions, a ValueError exception handling method is also added to deal with situations where the user may enter non-digits.

3. Final processing (use finally)

try:
    # 尝试执行可能引发异常的代码
    file = open('test.txt', 'r')
    content = file.read()
    print(content)
except FileNotFoundError:
    print("Error: File not found.")
finally:
    # 不管是否发生异常,都会执行的代码块
    file.close()  # 确保关闭文件,释放资源

The 'finally` block is used to ensure that an open file can be closed under any circumstances, regardless of whether an exception occurs.

6. Data structures and algorithms

1. List operations

A list is an ordered, mutable container that can contain elements of any type.

Create list
# 创建一个列表
my_list = [1, 2, 3, 4, 5]

# 访问列表元素
print(my_list[0])  # 输出列表中的第一个元素
print(my_list[-1])  # 输出列表中的最后一个元素
list slicing
# 列表切片操作
sliced_list = my_list[1:4]  # 从索引1到索引3(不包括4)切片
print(sliced_list)  # 输出 [2, 3, 4]
Add and remove elements
# 添加元素到列表尾部
my_list.append(6)

# 在特定位置插入元素
my_list.insert(2, 7)  # 在索引2处插入元素7

# 删除元素
my_list.remove(3)  # 删除元素3

2. Dictionary operations

A dictionary is an unordered collection of key-value pairs.

Create dictionary
# 创建一个字典
my_dict = {
    
    'name': 'Alice', 'age': 25, 'city': 'New York'}

# 访问字典元素
print(my_dict['name'])  # 输出 'Alice'
print(my_dict.get('age'))  # 输出 25
Add and remove key-value pairs
# 添加键值对
my_dict['gender'] = 'female'

# 删除键值对
del my_dict['city']
Iterate over dictionary
# 迭代字典的键
for key in my_dict:
    print(key, my_dict[key])

# 迭代字典的键值对
for key, value in my_dict.items():
    print(key, value)

3. Sorting algorithm

There are a variety of sorting algorithms available in Python, the most common of which are the built-in sorted() functions and the list sort() methods.

Sorting using the sorted() function
my_list = [4, 1, 7, 3, 9, 2]
sorted_list = sorted(my_list)  # 对列表进行排序
print(sorted_list)
Sorting using the sort() method of a list
my_list = [4, 1, 7, 3, 9, 2]
my_list.sort()  # 对列表进行排序(会修改原始列表)
print(my_list)

7. Network programming

Socket programming is a programming technique used to send and receive data over the network. It enables computer programs to communicate over a network, allowing data to be transferred between different devices. HTTP (Hypertext Transfer Protocol) is a protocol for transferring hypertext, usually used to transfer web pages and other resources between clients and servers.

In Python, you can use the built-in socket library for Socket programming, and use http.server or requests and other libraries for processing. HTTP protocol.

1. Socket programming example:

import socket

# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定IP和端口
server_socket.bind(('127.0.0.1', 8080))

# 监听连接
server_socket.listen(5)

while True:
    # 接受连接
    client_socket, addr = server_socket.accept()
    print(f"Connection from {
      
      addr} has been established!")

    # 发送和接收数据
    client_socket.send(bytes("Welcome to the server!", "utf-8"))
    data = client_socket.recv(1024)
    print("Received data:", data.decode("utf-8"))

    # 关闭连接
    client_socket.close()

2. HTTP protocol application examples:

There are many libraries in Python that can be used to handle HTTP requests and responses, such as therequests library.

import requests

# 发送GET请求
response = requests.get('https://api.example.com/data')

# 打印响应内容和状态码
print("Response:", response.text)
print("Status Code:", response.status_code)

# 发送POST请求
payload = {
    
    'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/post', data=payload)

# 打印响应内容和状态码
print("Response:", response.text)
print("Status Code:", response.status_code)

8. Database

In Python, there are a variety of libraries available for database operations, the most commonly used ones aresqlite3 (SQLite), MySQL Connector (MySQL), a>psycopg2 (PostgreSQL) and pymongo (MongoDB). The following example demonstrates how to use thesqlite3 library for database operations:

Connect to the SQLite database and perform operations:
import sqlite3

# 连接到SQLite数据库(如果不存在则会创建)
conn = sqlite3.connect('example.db')

# 创建一个游标对象,用于执行SQL语句
cursor = conn.cursor()

# 创建一个表
cursor.execute('''CREATE TABLE IF NOT EXISTS users 
                (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 25))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Bob', 30))

# 提交更改
conn.commit()

# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)

# 关闭连接
conn.close()

The above code creates a SQLite database named example.db, creates a table named users, and inserts data into the table . It then executes a query to retrieve all user data and prints out the results.

For other databases, the operation method is similar. Just select the appropriate library according to the database type and follow the corresponding documentation. For example, for MySQL, you can use the MySQL Connector library, for PostgreSQL, you can use the psycopg2 library, and for MongoDB, you can use the pymongo library , usage is similar to the example above.

Guess you like

Origin blog.csdn.net/matt45m/article/details/134670859