Python 入门¶
安装 Python¶
常见语法¶
# 输出
print("Hello, Python!")
# 变量
name = "Alice"
age = 18
# 条件语句
if age >= 18:
print("Adult")
else:
print("Child")
# 循环
for i in range(5):
print(i)
# 函数
def greet(person):
return f"Hello, {person}"
print(greet(name))
# 字典操作
person = {"name": "Alice", "age": 18}
print(person["name"])
# 列表切片
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # 输出 [2, 3, 4]
文件读写¶
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write("这是一个测试文件。\n")
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
安装与使用新库¶
# 安装 requests 库
pip install requests
# 升级 pip
pip install --upgrade pip
#安装完成后,在代码中使用 import:
import requests
response = requests.get("https://www.python.org")
print(response.status_code)