从入门到进阶,掌握最常用的Python语法与命令
Python是动态类型语言,变量无需声明类型。
# 定义变量
name = "Alice"
age = 25
height = 1.75
is_student = True
# 打印变量
print(name, age)
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
# for 循环
for i in range(5):
print(i)
# while 循环
count = 0
while count < 3:
print("计数:", count)
count += 1
def greet(name):
"""打招呼函数"""
return f"你好, {name}!"
print(greet("小明"))
fruits = ["苹果", "香蕉", "橙子"]
fruits.append("葡萄") # 添加元素
print(fruits[0]) # 访问第一个元素
print(len(fruits)) # 获取长度
person = {"name": "李华", "age": 30}
person["city"] = "北京" # 添加键值对
print(person.get("name")) # 安全获取值
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write("Hello, Python!")
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 导入整个模块
import math
print(math.sqrt(16))
# 导入特定函数
from datetime import datetime
now = datetime.now()
print(now)