python 编程常见试题解题详解82
一、基础语法1. 字符串格式化
```python
name = "小明"
age = 20
print("姓名:{}, 年龄:{}".format(name, age))
```
输出:姓名:小明,年龄:20
2. 列表生成式
```python
numbers = [x for x in range(10) if x % 2 == 0]
```
生成一个包含 0-9 之间偶数的列表:[0, 2, 4, 6, 8]
3. 字典操作
```python
my_dict = {"name": "小明", "age": 20}
my_dict["city"] = "北京"
print(my_dict)
```
输出:{'name': '小明', 'age': 20, 'city': '北京'}
二、函数与类4. 函数定义
```python
def sum(a, b):
return a + b
```
定义了一个求和函数。
5. 类定义
```python
class Person:
def __init__(self, name, age):
= name
= age
```
定义了一个 Person 类。
6. 对象操作
```python
p1 = Person("小明", 20)
print()
```
输出:小明
三、文件操作7. 文件读取
```python
with open("", "r") as f:
content = ()
```
读取文件 的内容。
8. 文件写入
```python
with open("", "w") as f:
("Hello World")
```
将字符串 Hello World 写入文件 。
四、错误处理9. 捕获异常
```python
try:
print(1 / 0)
except ZeroDivisionError:
print("被0除")
```
捕获除数为零的异常。
10. 抛出异常
```python
class MyError(Exception):
pass
raise MyError("自定义异常")
```
抛出一个自定义异常。
五、算法和数据结构11. 冒泡排序
```python
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(0, len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
```
对一个列表进行冒泡排序。
12. 二叉搜索树
```python
class Node:
def __init__(self, data):
= data
= None
= None
```
二叉搜索树的节点类。
13. 图的深度优先搜索
```python
def dfs(graph, start):
visited = set()
stack = [start]
while stack:
node = ()
if node not in visited:
(node)
for neighbor in graph[node]:
if neighbor not in visited:
(neighbor)
```
对一个图进行深度优先搜索。
六、其他14. 正则表达式
```python
import re
pattern = "[a-zA-Z]+"
match = (pattern, "Hello World")
print(())
```
匹配字符串中连续的字母。
15. 多线程
```python
import threading
def thread_task():
print("这是一个线程任务")
thread = (target=thread_task)
()
```
创建并启动一个线程。
2024-12-17
JavaScript eval:解密动态代码执行的魔盒与安全替代方案
https://jb123.cn/javascript/73117.html
深度解析PHP:从入门到精通,探索这门脚本语言的奥秘与未来
https://jb123.cn/jiaobenyuyan/73116.html
Python自动化Excel:告别繁琐,用代码解锁数据处理新境界
https://jb123.cn/python/73115.html
JavaScript核心知识:从前端魔法到全栈未来的必修之路
https://jb123.cn/javascript/73114.html
3ds MaxScript脚本语言学习完全指南:从入门到精通,解锁高效CG工作流!
https://jb123.cn/jiaobenyuyan/73113.html
热门文章
Python 编程解密:从谜团到清晰
https://jb123.cn/python/24279.html
Python编程深圳:初学者入门指南
https://jb123.cn/python/24225.html
Python 编程终端:让开发者畅所欲为的指令中心
https://jb123.cn/python/22225.html
Python 编程专业指南:踏上编程之路的全面指南
https://jb123.cn/python/20671.html
Python 面向对象编程学习宝典,PDF 免费下载
https://jb123.cn/python/3929.html