Python是一种广泛使用的高级编程语言,以其简洁优雅、易于学习和强大的库而闻名。无论你是一位经验丰富的程序员还是初学者,都可以从这种语言的丰富资源中受益。在本篇博客中,我将分享100个实用的Python代码示例,旨在帮助你掌握Python编程,并在日常工作中提高效率。
print("Hello, World!")
x = 10
y = "Python"
integer = 1
floating_point = 1.0
string = "text"
boolean = True
if x > 10:
print("Greater than 10")
else:
print("Less than or equal to 10")
for item in [1, 2, 3, 4, 5]:
print(item)
def greet(name):
print(f"Hello, {
name}!")
class Greeter:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {
self.name}!")
squares = [i * i for i in range(10)]
person = {
"name": "Alice", "age": 25}
person['age'] = 26 # 更新
with open('file.txt', 'r') as file:
content = file.read()
csv
模块处理CSV文件。import csv
# 写入CSV
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["name", "age"])
writer.writerow(["Alice", 30])
# 读取CSV
with open('output.csv', mode='r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
import json
# 序列化
data = {
"name": "John", "age": 30}
json_data = json.dumps(data)
# 反序列化
parsed_data = json.loads(json_data)
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df.head())
import numpy as np
arr = np.array([1, 2, 3])
print(arr + 1)
import matplotlib.pyplot as plt
# 生成数据
x = range(10)
y = [xi*2 for xi in x]
# 绘制图形
plt.plot(x, y)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Simple Plot')
plt.show()
import os
path = '.'
files_and_dirs = os.listdir(path) # 获取当前目录中的文件和子目录列表
print(files_and_dirs)
if not os.path.exists('new_directory'):
os.makedirs('new_directory')
file_path = 'example.txt'
if os.path.isfile(file_path):
print(f"The file {
file_path} exists.")
else:
print(f"The file {
file_path} does not exist.")
shutil
模块拷贝文件。import shutil
source = 'source.txt'
destination = 'destination.txt'
shutil.copyfile(source, destination)
try:
os.remove('unnecessary_file.txt')
except FileNotFoundError:
print("The file does not exist.")
requests
库发起HTTP GET请求。import requests
response = requests.get('https://api.github.com')
print(response.status_code)
import requests
url = 'http://example.com/somefile.txt'
r = requests.get(url)
with open('somefile.txt', 'wb') as f:
f.write(r.content)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to my web app!"
if __name__ == '__main__':
app.run(debug=True)
smtplib
发送电子邮件。import smtplib
from email.mime.text import MIMEText
smtp_server = "smtp.example.com"
port = 587 # For starttls
sender_email = "my@example.com"
receiver_email = "your@example.com"
password = input("Type your password and press enter: ")
message = MIMEText("This is the body of the email")
message['Subject'] = "Python Email Test"
message['From'] = sender_email
message['To'] = receiver_email
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.starttls(context=context)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
websocket-client
库连接WebSocket服务器。from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
text = "apple,banana,cherry"
words = text.split(',')
print(words)
message = "Python is Awesome!"
print(message.lower())
print(message.upper())
greeting = "Hello World!"
new_greeting = greeting.replace("World", "Python")
print(new_greeting)
re