50个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!

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
# 基于Python3、Scrapy爬取软考在线历年题库 ## 环境依赖 * Python3 * Scrapy库 * re库 * MySQL数据库 ## 安装使用 ```bash # 配置settings.py中数据库信息(导入数据库文件wx_rkpass.sql) # MYSQL INFO MYSQL_HOST = '127.0.0.1' MYSQL_PORT = 3306 MYSQL_DATABASE = 'wx_rkpass' MYSQL_USERNAME = 'root' MYSQL_PASSWORD = 'root' # 配置settings.py中图片保存路径 # 图片存储 IMAGES_STORE = './images' # 执行爬虫(爬取科目见下面文件介绍) $ 修改settings.py中pipelines (删除爬取科目前面的#号) $ scrapy crawl rkpassSpider # (可以更换其他科目) ``` ## 文件介绍 ```bash # 软件设计师(上午题) rkpassSpider.py # 网络工程师(上午题) wlMorningSpider.py # 信息系统监理师(上午题) xxMorningSpider.py # 数据库系统工程师(上午题) sjkMorningSpider.py # 软件评测师(上午题) rjpcsMorningSpider.py # 嵌入式系统设计师(上午题) qrsMorningSpider.py # 电子商务设计师(上午题) dzswMorningSpider.py # 多媒体应用设计师(上午题) mediaMorningSpider.py # 信息系统管理工程师(上午题) xxxtMorningSpider.py # 信息安全工程师(上午题) xxaqMorningSpider.py # 系统集成项目管理工程师(上午题) xtjcMorningSpider.py # 系统规划与管理师(上午题) xtghMorningSpider.py # 网络规划设计师(上午题) wlghMorningSpider.py # 系统架构设计师(上午题) xtjgMorningSpider.py # 系统分析师(上午题) xtfxMorningSpider.py # 信息系统项目管理师(上午题) xxxtxmMorningSpider.py ``` -------- 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! <项目介绍> 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT管理圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值