首页 > Python资料 博客日记

50个Python常见代码大全:学完这篇从Python小白到架构师

2024-09-29 14:00:06Python资料围观38

文章50个Python常见代码大全:学完这篇从Python小白到架构师分享给大家,欢迎收藏Python资料网,专注分享技术知识

50个Python常见代码大全:学完这篇从Python小白到架构师

Python是一门简单且强大的编程语言,广泛应用于各个领域。无论你是初学者还是经验丰富的开发者,掌握一些常见的代码段都能帮助你提升编程技能。在这篇博客中,我们将分享50个常见的Python代码段,助你从Python小白成长为架构师。

1. Hello World
print("Hello, World!")
2. 交换两个变量的值
a, b = 1, 2
a, b = b, a
3. 计算列表的平均值
numbers = [1, 2, 3, 4, 5]
average = sum(numbers) / len(numbers)
print(average)
4. 生成一个范围内的随机数
import random
random_number = random.randint(1, 100)
print(random_number)
5. 检查一个数是否为素数
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
6. 斐波那契数列
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b
fibonacci(10)
7. 反转字符串
s = "Hello, World!"
reversed_s = s[::-1]
print(reversed_s)
8. 检查回文
def is_palindrome(s):
    return s == s[::-1]
print(is_palindrome("racecar"))
9. 计算阶乘
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)
print(factorial(5))
10. 找到列表中的最大值和最小值
numbers = [1, 2, 3, 4, 5]
max_value = max(numbers)
min_value = min(numbers)
print(max_value, min_value)
11. 列表去重
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)
12. 字符串中单词计数
s = "hello world hello"
word_count = {}
for word in s.split():
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)
13. 合并两个字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
14. 计算两个日期之间的天数
from datetime import datetime
date1 = datetime(2022, 1, 1)
date2 = datetime(2022, 12, 31)
days_difference = (date2 - date1).days
print(days_difference)
15. 生成列表的所有排列
import itertools
numbers = [1, 2, 3]
permutations = list(itertools.permutations(numbers))
print(permutations)
16. 读取文件内容
with open('file.txt', 'r') as file:
    content = file.read()
    print(content)
17. 写入文件
with open('file.txt', 'w') as file:
    file.write("Hello, World!")
18. 发送HTTP请求
import requests
response = requests.get('https://api.github.com')
print(response.json())
19. 创建一个类和对象
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f'{self.name} says woof!')

my_dog = Dog('Rex')
my_dog.bark()
20. 异常处理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
21. Lambda函数
add = lambda x, y: x + y
print(add(2, 3))
22. 列表推导式
squares = [x**2 for x in range(10)]
print(squares)
23. 字典推导式
squares = {x: x**2 for x in range(10)}
print(squares)
24. 过滤列表中的偶数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
25. 计算字符串的长度
s = "Hello, World!"
length = len(s)
print(length)
26. 使用装饰器
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
27. 生成随机密码
import string
import random

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for i in range(length))

print(generate_password(12))
28. 使用Counter统计元素频率
from collections import Counter

data = ['a', 'b', 'c', 'a', 'b', 'b']
counter = Counter(data)
print(counter)
29. 合并多个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)
30. 获取当前日期和时间
from datetime import datetime
now = datetime.now()
print(now)
31. 将字符串转换为日期
from datetime import datetime
date_string = "2023-01-01"
date_object = datetime.strptime(date_string, '%Y-%m-%d')
print(date_object)
32. 计算两点之间的距离
import math

def distance(x1, y1, x2, y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

print(distance(0, 0, 3, 4))
33. 检查文件是否存在
import os
file_exists = os.path.exists('file.txt')
print(file_exists)
34. 获取文件大小
file_size = os.path.getsize('file.txt')
print(file_size)
35. 压缩文件
import zipfile

with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('file.txt')
36. 解压文件
with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted')
37. 计时器
import time

start_time = time.time()
# Some code to time
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
38. 多线程
import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
39. 读取JSON文件
import json

with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)
40. 写入JSON文件
data = {'name': 'John', 'age': 30}

with open('data.json', 'w') as file:
    json.dump(data, file)
41. 计算字符串的哈希值
import hashlib

s = "Hello, World!"
hash_object = hashlib.sha256(s.encode())
hash_hex = hash_object.hexdigest()
print(hash_hex)
42. 检查列表是否为空
numbers = []
is_empty = not numbers
print(is_empty)
43. 生成当前时间的时间戳
import time
timestamp = time.time()
print(timestamp)
44. 延迟执行
import time

```python
time.sleep(5)  # 延迟5秒
print("5 seconds have passed")
45. 使用正则表达式匹配字符串
import re

pattern = r'\d+'
s = "The number is 12345"
matches = re.findall(pattern, s)
print(matches)
46. 检查字符串是否包含子字符串
s = "Hello, World!"
contains = "World" in s
print(contains)
47. 列出目录中的所有文件
import os

files = os.listdir('.')
print(files)
48. 获取环境变量
import os

home_directory = os.getenv('HOME')
print(home_directory)
49. 执行外部命令
import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode())
50. 将数据写入CSV文件
import csv

data = [
    ['Name', 'Age', 'City'],
    ['Alice', 30, 'New York'],
    ['Bob', 25, 'San Francisco']
]

with open('people.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

总结

以上是50个常见的Python代码段,涵盖了从基本操作到高级用法的方方面面。通过掌握这些代码段,你可以更高效地进行Python编程,解决各种常见问题,并为进一步深入学习打下坚实的基础。希望这篇博客能够帮助你提升Python技能,成为一名出色的架构师!

如果你有任何问题或想了解更多内容,请在评论区留言。Happy coding!


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐