• python示例


    当涉及到Python的代码案例时,以下是一些示例,涵盖了不同方面的Python应用程序


    1. Hello World示例

    1. python
    2. print("Hello, World!")

    这是一个基本的Python脚本,它输出"Hello, World!"。你可以将此代码保存为.py文件并在命令行或集成开发环境中运行。
    2. 计算器应用程序

    以下是一个简单的计算器应用程序示例,用户可以输入两个数字和操作符,并得到计算结果。

     

    1. python
    2. def add(x, y):
    3. return x + y
    4. def subtract(x, y):
    5. return x - y
    6. def multiply(x, y):
    7. return x * y
    8. def divide(x, y):
    9. if y != 0:
    10. return x / y
    11. else:
    12. return "Error: Division by zero"
    13. num1 = float(input("Enter the first number: "))
    14. operator = input("Enter an operator (+, -, *, /): ")
    15. num2 = float(input("Enter the second number: "))
    16. if operator == "+":
    17. result = add(num1, num2)
    18. elif operator == "-":
    19. result = subtract(num1, num2)
    20. elif operator == "*":
    21. result = multiply(num1, num2)
    22. elif operator == "/":
    23. result = divide(num1, num2)
    24. else:
    25. result = "Error: Invalid operator"
    26. print("Result: ", result)

    用户可以输入两个数字和操作符来执行不同的数学运算,例如加法、减法、乘法和除法。
    3. 文件操作
    以下是一个示例,演示如何读取和写入文本文件。

    1. python
    2. # 写入文件
    3. with open("example.txt", "w") as file:
    4. file.write("Hello, World!\n")
    5. file.write("This is an example.")
    6. # 读取文件
    7. with open("example.txt", "r") as file:
    8. content = file.read()
    9. print(content)

    这个例子创建了一个名为example.txt的文本文件,并写入两行文本。然后它打开文件并读取文件内容,并将其打印到控制台上。


    4. 网络请求
    以下是一个使用Python发送HTTP GET请求的示例。

    1. python
    2. import requests
    3. url = "https://api.example.com/data"
    4. response = requests.get(url)
    5. if response.status_code == 200:
    6. data = response.json()
    7. print("Response data:", data)
    8. else:
    9. print("Error: Request failed with status code", response.status_code)

    在这个例子中,我们使用Python的requests库发送一个GET请求到指定的URL,并处理返回的响应。如果响应状态码为200,表示请求成功,我们将响应的JSON数据打印出来。否则,我们打印错误消息。


    5. 数据库访问
    以下是一个使用Python访问MySQL数据库的示例。

     

    1. python
    2. import mysql.connector
    3. # 连接到数据库
    4. conn = mysql.connector.connect(
    5. host="localhost",
    6. user="root",
    7. password="password",
    8. database="mydatabase"
    9. )
    10. # 执行查询
    11. cursor = conn.cursor()
    12. cursor.execute("SELECT * FROM customers")
    13. # 获取结果
    14. result = cursor.fetchall()
    15. for row in result:
    16. print(row)
    17. # 关闭连接
    18. cursor.close()
    19. conn.close()

    这个例子连接到本地MySQL数据库,并执行SELECT语句来获取customers表中的数据。然后,它遍历结果并打印每一行。
    以上示例涵盖了Python应用程序的不同方面,包括基本输出、数学计算、文件操作、网络请求和数据库访问。你可以根据自己的需求和项目的复杂性进一步扩展和改进这些示例。
    当然,请继续阅读更多的Python代码案例。


    6. Web应用程序开发(使用Flask框架)
    以下是一个使用Flask框架创建简单Web应用程序的示例。

     

    1. python
    2. from flask import Flask, render_template, request
    3. app = Flask(__name__)
    4. @app.route("/")
    5. def index():
    6. return "Hello, World!"
    7. @app.route("/hello/")
    8. def hello(name):
    9. return render_template("hello.html", name=name)
    10. @app.route("/form", methods=["GET", "POST"])
    11. def form():
    12. if request.method == "POST":
    13. name = request.form.get("name")
    14. return "Hello, " + name + "!"
    15. else:
    16. return render_template("form.html")
    17. if __name__ == "__main__":
    18. app.run()

    在这个例子中,我们使用Flask框架创建了一个简单的Web应用程序。它包含三个路由:


    - 根路由("/")返回"Hello, World!"。

    - "/hello/"路由接受一个名字作为参数,并使用渲染模板返回一个带有名字的页面。

    - "/form"路由处理GET和POST请求。GET请求返回一个包含表单的页面,POST请求接收表单提交的数据,并返回一个包含欢迎消息的响应。


    我们还需要创建相应的模板文件:hello.html和form.html。


    hello.html模板文件:

    1. html
    2. Hello
    3. Hello, {{ name }}!

    form.html模板文件:

    1. html
    2. Form
    3. Form
    4. Name:

    这个例子演示了如何使用Flask框架创建简单的Web应用程序,并处理路由和模板。


    7. 数据可视化(使用Matplotlib库)


    以下是一个使用Matplotlib库绘制折线图和散点图的示例。

    1. python
    2. import matplotlib.pyplot as plt
    3. # 折线图
    4. x = [1, 2, 3, 4, 5]
    5. y = [1, 4, 9, 16, 25]
    6. plt.plot(x, y)
    7. plt.xlabel("X")
    8. plt.ylabel("Y")
    9. plt.title("Line Chart")
    10. plt.show()
    11. # 散点图
    12. x = [1, 2, 3, 4, 5]
    13. y = [1, 4, 9, 16, 25]
    14. plt.scatter(x, y)
    15. plt.xlabel("X")
    16. plt.ylabel("Y")
    17. plt.title("Scatter Plot")
    18. plt.show()

    这个例子展示了如何使用Matplotlib库绘制简单的折线图和散点图。我们可以指定x轴和y轴的值,并使用plot函数和scatter函数绘制相应的图形。


    8. 多线程编程


    以下是一个使用Python多线程编程的示例,展示了如何同时执行多个任务。

    1. python
    2. import threading
    3. import time
    4. def task1():
    5. for _ in range(5):
    6. print("Task 1")
    7. time.sleep(1)
    8. def task2():
    9. for _ in range(5):
    10. print("Task 2")
    11. time.sleep(1)
    12. # 创建线程
    13. thread1 = threading.Thread(target=task1)
    14. thread2 = threading.Thread(target=task2)
    15. # 启动线程
    16. thread1.start()
    17. thread2.start()
    18. # 等待线程完成
    19. thread1.join()
    20. thread2.join()
    21. print("All tasks completed")

    这个例子创建了两个线程,每个线程执行一个任务。通过启动这两个线程,它们可以同时执行,而不是按顺序执行。最后,主线程等待这两个线程完成后才输出"所有任务完成"。


    以上示例涵盖了Python应用程序的不同方面,包括Web应用程序开发、数据可视化、文件操作、网络请求和多线程编程。你可以根据自己的需求和项目的复杂性进一步扩展和改进这些示例。

  • 相关阅读:
    iPhone15发布,苹果和台积电的牛皮都破了,3纳米没那么神奇
    SJ/T 11294-2018 防静电地坪涂料检测
    vue provide inject使用
    【老生谈算法】自动控制中常用的Matlab函数合集——自动控制
    手撸Router,还要啥Router框架?react-router/vue-router躺一边去
    【torchvision】 torchvision.datasets.ImageFolder
    【GEE】基于GEE进行非监督学习
    【优化调度】基于蜜蜂算法实现经济调度问题附matlab代码
    公司职位描述
    【Java】ListIterator
  • 原文地址:https://blog.csdn.net/onebound/article/details/132044444