python代码实例

当提到 Python 代码实例时,这可以涉及各种不同的应用场景。

Hello World:

python
print("Hello, World!")

变量和运算:

python
# 变量和运算 a = 5 b = 3 result = a + b print(f"The result is: {result}")

条件语句:

python
# 条件语句 age = 18 if age >= 18: print("You are an adult.") else: print("You are a minor.")

循环:

python
# 循环 for i in range(5): print(f"Count: {i}")

函数:

python
# 函数 def greet(name): print(f"Hello, {name}!") greet("Alice")

列表:

python
# 列表 fruits = ["apple", "banana", "orange"] print("Fruits:", fruits)

字典:

python
# 字典 person = {"name": "John", "age": 25, "city": "New York"} print("Person:", person)

文件操作:

python
# 文件操作 with open("example.txt", "w") as file: file.write("This is an example.")

异常处理:

python
# 异常处理 try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")

模块导入:

python
# 模块导入 import math print("Square root of 16:", math.sqrt(16))

面向对象编程:

python
# 面向对象编程 class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} says Woof!") my_dog = Dog("Buddy", 3) my_dog.bark()

多线程:

python
# 多线程 import threading import time def print_numbers(): for i in range(5): time.sleep(1) print(i) def print_letters(): for letter in "ABCDE": time.sleep(1) print(letter) thread1 = threading.Thread(target=print_numbers) thread2 = threading.Thread(target=print_letters) thread1.start() thread2.start() thread1.join() thread2.join()

Web 开发:

python
# Web 开发 from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True)

数据科学示例:

python
# 数据科学示例 import pandas as pd import matplotlib.pyplot as plt data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 40]} df = pd.DataFrame(data) plt.bar(df['Name'], df['Age']) plt.xlabel('Name') plt.ylabel('Age') plt.title('Age distribution') plt.show()

机器学习示例:

python
# 机器学习示例 from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier iris = datasets.load_iris() X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2) model = KNeighborsClassifier(n_neighbors=3) model.fit(X_train, y_train) accuracy = model.score(X_test, y_test) print(f"Accuracy: {accuracy}")