20 个超实用的 Python 代码示例

2024-12-31 05:52:20   小编

20 个超实用的 Python 代码示例

Python 作为一种广泛使用的编程语言,拥有丰富的功能和强大的库。以下为您展示 20 个超实用的 Python 代码示例,帮助您提升编程技能和解决实际问题。

  1. 打印斐波那契数列
def fibonacci(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
fibonacci(100)
  1. 计算阶乘
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)
print(factorial(5))
  1. 检查回文
def is_palindrome(s):
    return s == s[::-1]
print(is_palindrome('race a car'))
  1. 列表去重
my_list = [1, 2, 2, 3, 3, 3]
new_list = list(set(my_list))
print(new_list)
  1. 计算平均值
def average(numbers):
    return sum(numbers) / len(numbers)
print(average([1, 2, 3, 4, 5]))
  1. 字符串反转
s = "Hello, World!"
reversed_s = s[::-1]
print(reversed_s)
  1. 冒泡排序
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1] :
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
  1. 二分查找
def binary_search(arr, x):
    low = 0
    high = len(arr) - 1

    while low <= high:
        mid = (low + high) // 2

        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            low = mid + 1
        else:
            high = mid - 1

    return -1
arr = [1, 3, 5, 7, 9, 11]
print(binary_search(arr, 7))
  1. 文件读写
# 写入文件
with open('file.txt', 'w') as f:
    f.write('Hello, Python!')

# 读取文件
with open('file.txt', 'r') as f:
    content = f.read()
    print(content)
  1. 生成随机数
import random
print(random.randint(1, 10))
  1. 计算圆周率
import math
def calculate_pi(n):
    sum = 0
    for i in range(n):
        sum += (-1)**i / (2 * i + 1)
    return 4 * sum
print(calculate_pi(1000000))
  1. 爬取网页内容
import requests
response = requests.get('https://www.example.com')
print(response.text)
  1. 发送邮件
import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'your_email@example.com'
    msg['To'] = to

    s = smtplib.SMTP('smtp.example.com')
    s.send_message(msg)
    s.quit()
send_email('Hello', 'This is a test email.', 'recipient@example.com')
  1. 多线程示例
import threading
import time

def thread_function(name):
    print(f"Thread {name} is running")
    time.sleep(2)
    print(f"Thread {name} completed")

thread1 = threading.Thread(target=thread_function, args=("Thread 1",))
thread2 = threading.Thread(target=thread_function, args=("Thread 2",))

thread1.start()
thread2.start()

thread1.join()
thread2.join()
  1. 字典操作
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['a'])
my_dict['d'] = 4
print(my_dict)
  1. 正则表达式匹配
import re
text = "Hello, my email is example@example.com"
match = re.search(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
if match:
    print(match.group())
  1. 面向对象编程
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hello, I'm {self.name} and I'm {self.age} years old.")

person1 = Person("John", 25)
person1.introduce()
  1. 异常处理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
  1. 数据可视化
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Simple Plot')
plt.show()
  1. 数据结构 - 栈
class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()

    def is_empty(self):
        return len(self.items) == 0

stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop())

这些示例涵盖了 Python 编程的多个方面,希望对您有所帮助。不断练习和探索,您将能够熟练运用 Python 解决更多复杂的问题。

TAGS: Python 实用技巧 Python 代码示例 Python 语言 超实用代码

欢迎使用万千站长工具!

Welcome to www.zzTool.com