# 变量定义(无需声明类型)name = "Alice" age = 25height = 1.68is_student = False# 同时赋值多个变量x, y, z = 1, 2, 3a = b = c = 0# 变量命名规则user_name = "Bob" # 推荐:下划线命名UserName = "Carol" # 也可用,但通常用于类名# 1name = "Dave" # 错误:不能以数字开头# my-name = "Eve" # 错误:不能含连字符
# 整数age = 25negative = -10# 浮点数price = 19.99rate = 0.05# 基本运算a = 10 + 5 # 加 → 15b = 10 - 5 # 减 → 5c = 10 * 5 # 乘 → 50d = 10 / 3 # 除 → 3.333...e = 10 // 3 # 整除 → 3f = 10 % 3 # 取余 → 1g = 2 ** 3 # 幂 → 8
# 定义字符串name = "Python"greeting = 'Hello'multi_line = """这是多行字符串"""# 字符串拼接full_name = "Hello" + " " + "World"# 常用方法text = " Hello World "text.strip() # 去空格 → "Hello World"text.lower() # 转小写 → " hello world "text.upper() # 转大写 → " HELLO WORLD "text.replace("H", "h") # 替换 → " hello World "# 格式化字符串name = "Alice"age = 25msg1 = f"My name is {name}, age {age}" # 推荐msg2 = "My name is {}, age {}".format(name, age)
# 创建列表fruits = ["apple", "banana", "orange"]numbers = [1, 2, 3, 4, 5]mixed = [1, "two", 3.0, True]# 访问元素fruits[0] # 第一个 → "apple"fruits[-1] # 最后一个 → "orange"fruits[1:3] # 切片 → ["banana", "orange"]# 修改列表fruits.append("grape") # 末尾添加fruits.insert(0, "pear") # 指定位置插入fruits.remove("banana") # 删除元素popped = fruits.pop() # 弹出末尾元素# 常用操作len(fruits) # 长度fruits.index("apple") # 查找索引"apple" in fruits # 是否存在 → True# 列表推导式squares = [x**2 for x in range(5)] # → [0, 1, 4, 9, 16]
# 创建元组(不可修改的列表)point = (3, 5)colors = ("red", "green", "blue")# 访问元素point[0] # → 3point[-1] # → 5# 元组解包x, y = point # x=3, y=5# 注意:元组不能修改# point[0] = 10 # 错误!
# 创建字典person = { "name": "Alice", "age": 25, "city": "Beijing"}# 访问值person["name"] # → "Alice"person.get("age") # → 25person.get("job", "N/A") # 默认值 → "N/A"# 修改字典person["age"] = 26 # 修改person["job"] = "Engineer" # 新增del person["city"] # 删除# 常用操作person.keys() # 所有键person.values() # 所有值person.items() # 键值对# 遍历字典for key, value in person.items(): print(f"{key}: {value}")
# 布尔值is_true = Trueis_false = False# 比较运算10 > 5 # → True10 == 10 # → True10 != 5 # → True10 <= 10 # → True# 逻辑运算True and False # → FalseTrue or False # → Truenot True # → False# 真值判断bool(0) # → Falsebool("") # → Falsebool([]) # → Falsebool(None) # → False
score = 85if score >= 90: print("优秀")elif score >= 80: print("良好")elif score >= 60: print("及格")else: print("不及格")# 简写形式result = "通过" if score >= 60 else "不通过"
# 遍历列表fruits = ["apple", "banana", "orange"]for fruit in fruits: print(fruit)# 遍历范围for i in range(5): # 0 到 4 print(i)for i in range(2, 6): # 2 到 5 print(i)for i in range(0, 10, 2): # 步长为 2 → 0, 2, 4, 6, 8 print(i)# 带索引遍历for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")# break 和 continuefor i in range(10): if i == 3: continue # 跳过本次 if i == 7: break # 退出循环 print(i)
# 基本 whilecount = 0while count < 5: print(count) count += 1# while-elsen = 0while n < 3: print(n) n += 1else: print("循环结束") # 正常结束时执行
| | | |
|---|
| | [1, 2, 3] | |
| | (1, 2, 3) | |
| | {"a": 1} | |
| | "hello" | |
# 1. 列表拷贝a = [1, 2, 3]b = a # 引用同一对象!b.append(4)print(a) # → [1, 2, 3, 4] 意外被修改b = a.copy() # 正确:创建新副本# 2. == 与 isa = [1, 2, 3]b = [1, 2, 3]a == b # → True (值相等)a is b # → False (不是同一对象)# 3. 可变默认参数(避免!)def bad_func(item, items=[]): # 危险! items.append(item) return itemsdef good_func(item, items=None): if items is None: items = [] items.append(item) return items
提示:收藏本文,写代码时随时对照查阅。熟练后可以尝试用这些语法完成小项目,实践中记忆更深刻。