20个常用的Python脚本

以下是20个常用的Python脚本示例:

  1. 计算阶乘
python 复制代码
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))
  1. 斐波那契数列
python 复制代码
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))
  1. 判断素数
python 复制代码
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(7))
  1. 字符串反转
python 复制代码
def reverse_string(s):
    return s[::-1]

print(reverse_string("hello"))
  1. 字符串大小写转换
python 复制代码
def convert_case(s, case):
    if case == "upper":
        return s.upper()
    elif case == "lower":
        return s.lower()
    else:
        return s

print(convert_case("Hello", "lower"))
  1. 字符串替换
python 复制代码
def replace_string(s, old, new):
    return s.replace(old, new)

print(replace_string("hello world", "world", "python"))
  1. 列表排序
python 复制代码
def sort_list(lst):
    return sorted(lst)

print(sort_list([3, 1, 4, 2]))
  1. 列表去重
python 复制代码
def remove_duplicates(lst):
    return list(set(lst))

print(remove_duplicates([1, 2, 2, 3, 4, 4]))
  1. 列表合并
python 复制代码
def merge_lists(lst1, lst2):
    return lst1 + lst2

print(merge_lists([1, 2, 3], [4, 5, 6]))
  1. 列表切片
python 复制代码
def slice_list(lst, start, end):
    return lst[start:end]

print(slice_list([1, 2, 3, 4, 5], 1, 4))
  1. 字典键值对调换
python 复制代码
def swap_dict(d):
    return {v: k for k, v in d.items()}

print(swap_dict({"a": 1, "b": 2, "c": 3}))
  1. 计算圆的面积和周长
python 复制代码
import math

def circle_area_circumference(radius):
    area = math.pi * radius**2
    circumference = 2 * math.pi * radius
    return area, circumference

print(circle_area_circumference(5))
  1. 计算两个数的最大公约数和最小公倍数
python 复制代码
def gcd_lcm(a, b):
    gcd = a if b == 0 else gcd_lcm(b, a % b)
    lcm = a * b // gcd
    return gcd, lcm

print(gcd_lcm(12, 18))
  1. 计算矩阵乘法
python 复制代码
def matrix_multiply(A, B):
    return [[sum(a * b for a, b in zip(row_A, col_B)) for col_B in zip(*B)] for row_A in A]

print(matrix_multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]))
  1. 计算阶乘和
python 复制代码
def factorial_sum(n):
    return sum(range(1, n+1))

print(factorial_sum(5))
  1. 生成斐波那契数列的前n项
python 复制代码
def generate_fibonacci(n):
    return [fibonacci(i) for i in range(n)]

print(generate_fibonacci(10))
  1. 生成随机数列表
python 复制代码
import random

def generate_random_list(n, start, end):
    return [random.randint(start, end) for _ in range(n)]

print(generate_random_list(5, 1, 10))
  1. 生成九九乘法表
python 复制代码
def print_multiplication_table():
    for i in range(1, 10):
        for j in range(1, i+1):
            print(f"{j}x{i}={i*j}", end="\t")
        print()

print_multiplication_table()
  1. 生成随机密码
python 复制代码
import random
import string

def generate_password(length):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

print(generate_password(8))
  1. 生成随机字符串
python 复制代码
import random
import string

def generate_random_string(length):
    return ''.join(random.choices(string.ascii_letters, k=length))

print(generate_random_string(8))
相关推荐
大数据魔法师30 分钟前
Streamlit(二十三)- 教程(二)- 动态导航
python·web
yyuuuzz3 小时前
独立站的技术基础与常见运维问题
大数据·运维·服务器·网络·数据库·aws
心中有国也有家3 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
卷毛的技术笔记4 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥4 小时前
匿名函数 lambda + 高阶函数
java·python·算法
vb2008114 小时前
FastAPI APIRouter
开发语言·python
adrninistrat0r5 小时前
Java调用链MCP分析工具
java·python·ai编程
杨充5 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
meilindehuzi_a6 小时前
深入浅出数据结构:Python 字典(Dict)与集合(Set)的哈希表底层全链路追踪
数据结构·python·散列表
Lucas凉皮6 小时前
20243408 2025-2026-2 《Python程序设计》综合实践报告
python·实验报告