变量定义
name = "Alice"
age = 30
数据类型
print(type(name))
print(type(age))
运算符
print(10 + 5) 15
控制流语句
if age > 18:
print("成年人")
else:
print("未成年人")
函数定义
def greet(name):
print("Hello,", name)
greet("Bob") Hello, Bob
列表
my_list = [1, 2, 3, 4]
元组
my_tuple = (1, 2, 3)
字典
my_dict = {"name": "Alice", "age": 30}
集合
my_set = {1, 2, 3}
import math
print(math.sqrt(25)) 5.0
自定义模块
import my_module
my_module.greet("Alice") Hello, Alice
写入文件
with open("my_file.txt", "w") as f:
f.write("Hello, world!")
读取文件
with open("my_file.txt", "r") as f:
content = f.read()
print(content) Hello, world!
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("汪汪")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) Buddy
my_dog.bark() 汪汪
import sqlite3
conn = sqlite3.connect("my_database.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
conn.commit()
conn.close()
上一篇:python3.11pip安装
下一篇:python3.11.1安装教程