1.下载 Visual Studio Code 安装Python扩展

2.新建.py文件,输入 print("Hello, Python!") 运行
print("Hello, Python!")

3.基础语法
1.数据类型转换
函数 作用 示例
int(x) 转为整数 int("10") → 10
float(x) 转为浮点数 float("3.14") → 3.14
str(x) 转为字符串 str(42) → "42"
bool(x) 转为布尔值 bool(0) → False
list(x) 转为列表 list("hi") → ['h', 'i']
tuple(x) 转为元组 tuple([1,2]) → (1,2)
set(x) 转为集合(去重) set([1,1,2]) → {1,2}
dict(x) 转为字典 dict([("a",1)]) → {'a':1}
2.输入输出
input() 的返回值永远是字符串name = "Alice"
age = 30
print(f"我的名字是 {name},年龄是 {age}。") # 输出: 我的名字是 Alice,年龄是 30。# 表达式计算
print(f"明年我 {age + 1} 岁。") # 输出: 明年我 31 岁。
# 格式化数字
pi = 3.1415926
print(f"π 约等于 {pi:.2f}") # 输出: π 约等于 3.14
# 调用方法
print(f"名字大写: {name.upper()}") # 输出: 名字大写: ALICE
3.lambda
lambda 参数: 表达式
过度使用复杂的 lambda 会降低代码可读性,建议在适当场景使用,保持逻辑简单。
4. 文件读写操作和异常处理
一、文件读写操作1. 打开文件:open()
file = open(文件路径, 模式, 编码)模式:
'r':读取(默认)
'w':写入(覆盖原有内容)
'a':追加(在文件末尾添加)
'x':创建新文件,若文件已存在则报错
'b':二进制模式(与其他模式组合使用,如 'rb')
'+':读写模式(与其他模式组合使用,如 'r+')
编码:常用 'utf-8'、'gbk' 等(文本模式下使用)2. 读取文件
# 示例文件内容:
# Hello
# World
# Python
# 方式 1:读取整个文件
with open('example.txt', 'r', encoding='utf-8') as f:content = f.read() # 读取全部内容为字符串print(content) # 输出: Hello\nWorld\nPython
# 方式 2:逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:lines = f.readlines() # 读取所有行,返回列表for line in lines:print(line.strip()) # 输出每行(去除换行符)
# 方式 3:逐行迭代(推荐,节省内存)
with open('example.txt', 'r', encoding='utf-8') as f:for line in f: # 直接迭代文件对象print(line.strip())
3. 写入文件
# 写入模式 'w'(覆盖原有内容)
with open('output.txt', 'w', encoding='utf-8') as f:f.write("Hello\n") # 写入字符串f.writelines(["World\n", "Python\n"]) # 写入多行(列表)
# 追加模式 'a'
with open('output.txt', 'a', encoding='utf-8') as f:f.write("Append this line.\n")
4. 二进制文件操作
# 读取二进制文件(如图片)
with open('image.jpg', 'rb') as f:data = f.read()
# 写入二进制文件
with open('copy.jpg', 'wb') as f:f.write(data)
5. 文件指针操作
with open('example.txt', 'r', encoding='utf-8') as f:print(f.tell()) # 0:初始位置f.read(3) # 读取前3个字符print(f.tell()) # 3:当前位置f.seek(0) # 回到文件开头二、异常处理
1.常用异常类型
FileNotFoundError:文件不存在
PermissionError:权限不足
IsADirectoryError:路径指向目录而非文件
UnicodeDecodeError:读取文件时编码错误
2.高级异常处理
try:with open('data.txt', 'r', encoding='utf-8') as f:data = f.read()num = int(data) # 可能引发 ValueError
except FileNotFoundError as e:print(f"错误:{e}") # 打印详细错误信息
except ValueError:print("文件内容无法转换为整数!")
except Exception as e:print(f"未知错误:{e}") # 捕获其他所有异常
else:print(f"成功读取并转换:{num}") # 没有异常时执行
finally:print("无论如何都会执行这里")