Python是一门简单且强大的编程语言,广泛应用于各个领域。无论你是初学者还是经验丰富的开发者,掌握一些常见的代码段都能帮助你提升编程技能。在这篇博客中,我们将分享50个常见的Python代码段,助你从Python小白成长为架构师。
print("Hello, World!")
a, b = 1, 2
a, b = b, a
numbers = [1, 2, 3, 4, 5]
average = sum(numbers) / len(numbers)
print(average)
import random
random_number = random.randint(1, 100)
print(random_number)
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
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(10)
s = "Hello, World!"
reversed_s = s[::-1]
print(reversed_s)
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("racecar"))
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
numbers = [1, 2, 3, 4, 5]
max_value = max(numbers)
min_value = min(numbers)
print(max_value, min_value)
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)
s = "hello world hello"
word_count = {}
for word in s.split():
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
from datetime import datetime
date1 = datetime(2022, 1, 1)
date2 = datetime(2022, 12, 31)
days_difference = (date2 - date1).days
print(days_difference)
import itertools
numbers = [1, 2, 3]
permutations = list(itertools.permutations(numbers))
print(permutations)
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('file.txt', 'w') as file:
file.write("Hello, World!")
import requests
response = requests.get('https://api.github.com')
print(response.json())
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()
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
add = lambda x, y: x + y
print(add(2, 3))
squares = [x**2 for x in range(10)]
print(squares)
squares = {x: x**2 for x in range(10)}
print(squares)
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
s = "Hello, World!"
length = len(s)
print(length)
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()
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))
from collections import Counter
data = ['a', 'b', 'c', 'a', 'b', 'b']
counter = Counter(data)
print(counter)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)
from datetime import datetime
now = datetime.now()
print(now)
from datetime import datetime
date_string = "2023-01-01"
date_object = datetime.strptime(date_string, '%Y-%m-%d')
print(date_object)
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(distance(0, 0, 3, 4))
import os
file_exists = os.path.exists('file.txt')
print(file_exists)
file_size = os.path.getsize('file.txt')
print(file_size)
import zipfile
with zipfile.ZipFile('archive.zip', 'w') as zipf:
zipf.write('file.txt')
with zipfile.ZipFile('archive.zip', 'r') as zipf:
zipf.extractall('extracted')
import time
start_time = time.time()
# Some code to time
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
data = {'name': 'John', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)
import hashlib
s = "Hello, World!"
hash_object = hashlib.sha256(s.encode())
hash_hex = hash_object.hexdigest()
print(hash_hex)
numbers = []
is_empty = not numbers
print(is_empty)
import time
timestamp = time.time()
print(timestamp)
import time
```python
time.sleep(5) # 延迟5秒
print("5 seconds have passed")
import re
pattern = r'\d+'
s = "The number is 12345"
matches = re.findall(pattern, s)
print(matches)
s = "Hello, World!"
contains = "World" in s
print(contains)
import os
files = os.listdir('.')
print(files)
import os
home_directory = os.getenv('HOME')
print(home_directory)
import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode())
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!