Python必会的50个代码操作
学习Python时,掌握一些常用的程序操作非常重要。以下是50个Python必会的程序操作,主要包括基础语法、数据结构、函数和文件操作等。
1. Hello World
print("Hello, World!")
2. 注释
# 这是单行注释
'''
这是多行注释
'''
3. 变量赋值
x = 10
y = 20.5
name = "Python"
4. 类型转换
x = int(10.5) # 转为整数
y = float("20.5") # 转为浮点数
5. 输入输出
name = input("Enter your name: ")
print("Hello", name)
6. 条件语句
if x > y:
print("x is greater")
elif x < y:
print("y is greater")
else:
print("x and y are equal")
7. 循环
for循环
for i in range(5):
print(i)
while循环
i = 0
while i < 5:
print(i)
i += 1
8. 列表操作
lst = [1, 2, 3, 4]
lst.append(5)
lst.remove(3)
lst[0] = 10
9. 字典操作
dic = {"name": "Alice", "age": 25}
dic["age"] = 26
dic["city"] = "New York"
10. 元组操作
tup = (1, 2, 3)
print(tup[0])
11. 集合操作
s = {1, 2, 3}
s.add(4)
s.remove(2)
12. 函数定义
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
13. 返回值
def add(x, y):
return x + y
print(add(3, 4))
14. 匿名函数(Lambda)
square = lambda x: x**2
print(square(5))
15. 递归
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
16. 异常处理
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
17.文件操作
读取文件
with open("file.txt", "r") as file:
content = file.read()
print(content)
写入文件
with open("file.txt", "w") as file:
file.write("Hello, World!")
18. 模块导入
import math
print(math.sqrt(16))
19. 类和对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
person = Person("Alice", 25)
person.greet()
20. 继承
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def greet(self):
super().greet()
print(f"I'm in grade {self.grade}.")
student = Student("Bob", 20, "A")
student.greet()
21. 列表推导式
squares = [x**2 for x in range(10)]
22. 字典推导式
square_dict = {x: x**2 for x in range(5)}
23. 集合推导式
unique_squares = {x**2 for x in range(5)}
24. 生成器
def generate_numbers(n):
for i in range(n):
yield i
gen = generate_numbers(5)
for num in gen:
print(num)
25. 正则表达式
import re
pattern = r'\d+'
text = "There are 123 apples"
result = re.findall(pattern, text)
print(result)
26. 日期和时间
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
27. 排序
lst = [5, 3, 8, 6]
lst.sort() # 升序
lst.sort(reverse=True) # 降序
28. 枚举
lst = ["a", "b", "c"]
for index, value in enumerate(lst):
print(index, value)
29. zip函数
lst1 = [1, 2, 3]
lst2 = ["a", "b", "c"]
zipped = zip(lst1, lst2)
for item in zipped:
print(item)
30. all()和any()
lst = [True, True, False]
print(all(lst)) # False
print(any(lst)) # True
31. 切片
lst = [0, 1, 2, 3, 4]
print(lst[1:4]) # 输出 [1, 2, 3]
32. 列表拼接
lst1 = [1, 2]
lst2 = [3, 4]
lst3 = lst1 + lst2
33. 内存管理(del)
lst = [1, 2, 3]
del lst[1] # 删除索引1的元素
34. 函数式编程(map, filter, reduce)
from functools import reduce
lst = [1, 2, 3, 4]
result = map(lambda x: x**2, lst) # 平方每个元素
result = filter(lambda x: x % 2 == 0, lst) # 过滤偶数
result = reduce(lambda x, y: x + y, lst) # 求和
35. 列表展开
lst = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in lst for item in sublist]
36. 接口
from abc import ABC, abstractmethod
class MyInterface(ABC):
@abstractmethod
def do_something(self):
pass
37. 用from import方式导入部分模块
from math import pi
print(pi)
38. 命令行参数
import sys
print(sys.argv) # 获取命令行参数
39. 生成随机数
import random
print(random.randint(1, 100)) # 生成1到100的随机整数
40. 计时器(time模块)
import time
start_time = time.time()
time.sleep(2) # 等待2秒
end_time = time.time()
print(f"Duration: {end_time - start_time} seconds")
41. 进程与线程
from threading import Thread
def print_hello():
print("Hello from thread")
t = Thread(target=print_hello)
t.start()
42. 环境变量
import os
os.environ["MY_VAR"] = "some_value"
print(os.environ["MY_VAR"])
43. pip安装包
pip install package_name
44. 虚拟环境
python -m venv myenv
source myenv/bin/activate # 激活
deactivate # 退出
45. 命令行解析(argparse)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
print(f"Hello {args.name}")
46. JSON解析
import json
data = '{"name": "Alice", "age": 25}'
obj = json.loads(data)
print(obj["name"])
47. 多线程并发
from concurrent.futures import ThreadPoolExecutor
def task(x):
return x * 2
with ThreadPoolExecutor() as executor:
results = executor.map(task, [1, 2, 3])
print(list(results))
48. 装饰器
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def greet():
print("Hello!")
greet()
49. 文件遍历
import os
for file_name in os.listdir("my_dir"):
print(file_name)
50. 上下文管理器(with语句)
with open("file.txt", "r") as file:
content = file.read()
print(content)