Python基础知识
控制结构
条件语句
age = 20
if age >= 18:
print("成年人")
elif age >= 12:
print("青少年")
else:
print("儿童")
循环语句
For循环
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
While循环
i = 1
while i < 6:
print(i)
i += 1
函数
def greet(name="World"):
print(f"Hello, {name}!")
greet("Alice") # 输出: Hello, Alice!
greet() # 输出: Hello, World!
数据结构
列表(Lists)
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出: [1, 2, 3, 4]
元组(Tuples)
my_tuple = (1, 2, 3)
print(my_tuple[0]) # 输出: 1
字典(Dictionaries)
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # 输出: Alice
集合(Sets)
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出: {1, 2, 3, 4}
模块和包
导入模块:
import math
print(math.sqrt(16)) # 输出: 4.0
创建包:在文件夹内放置__init__.py
文件。
异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
finally:
print("执行完毕")
文件操作
读取文件:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
写入文件:
with open('example.txt', 'w') as file:
file.write("这是一个测试文本。")
常用标准库
os
提供操作系统相关功能。
import os
print(os.getcwd()) # 打印当前工作目录
sys
访问与Python解释器紧密相关的变量和函数。
import sys
print(sys.version) # 打印Python版本信息
datetime
处理日期和时间。
from datetime import datetime
now = datetime.now()
print(now)