用简单的话来说,Python中的关键字就是Python 已经存在的特殊词语,这些特殊的词语在Python中都有自己固定的意思,既然是Python固定好的,那么就不能随便使用,不能随便给变量来命名,或者给函数命名,在Python中一共有39个关机那字,而且其中有4个事软关键字。
软关键字的意思就是只有在特定的场景下才是关键字,例如在一些模式匹配才会生效,平时可以当做普通名字来使用,不过建议也不要乱用,避免踩坑!
:
,或者条件表达式写错(比如把==
写成=
)。score = 85
if score >= 60:
print("及格啦!") # 条件满足,会执行
score = 85
subject = "数学"
if score >= 90 and subject == "数学":
print("获得数学优秀奖励!")
if
配对使用,条件不满足时执行的代码块;也能在循环后面用,循环正常结束后执行(没被 break 打断)。if
或者循环配对;缩进容易搞错。score = 50
if score >= 60:
print("及格啦!")
else:
print("不及格,要加油哦!") # 条件不满足,执行这里
numbers = [1, 2, 3, 4]
target = 5
for num in numbers:
if num == target:
print("找到目标啦!")
break
else: # 循环正常结束(没break),执行这里
print("没找到目标...") # 这里会执行,因为target不在列表里
if
和else
之间。else if
,这是错误的,必须用elif
;后面也要加冒号:
。score = 75
if score >= 90:
print("A等级")
elif score >= 80:
print("B等级")
elif score >= 70:
print("C等级")
else:
print("D等级") # 输出C等级
:
;在循环里修改正在遍历的列表,可能导致结果异常。fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(fruit) # 依次打印每个水果
person = {"名字": "张三", "年龄": 20, "性别": "男"}
for key, value in person.items():
print(f"{key}: {value}") # 打印键值对
:
。target = 5
while True: # 无限循环,直到猜对
guess = int(input("猜一个数字:"))
if guess == target:
print("猜对啦!")
break # 退出循环
else:
print("猜错了,再试试!")
for i in range(1, 6):
if i == 3:
break # 遇到3就结束循环
print(i) # 打印1, 2
for i in range(1, 6):
if i % 2 == 0:
continue # 是偶数,跳过本次循环
print(i) # 打印1, 3, 5
_
表示任意值。status = "success"
match status:
case "success":
print("操作成功!") # 匹配成功,执行这里
case "fail":
print("操作失败!")
case _: # 匹配其他任意值
print("未知状态")
point = (2, 3)
match point:
case (0, 0):
print("原点")
case (x, 0):
print(f"在x轴上,x坐标是{x}")
case (0, y):
print(f"在y轴上,y坐标是{y}")
case (x, y):
print(f"坐标是({x}, {y})") # 匹配任意坐标,这里会执行
|
表示或关系。num = 5
match num:
case 1 | 2 | 3: # 匹配1或2或3
print("小数字")
case 4 | 5 | 6:
print("中数字") # 匹配5,执行这里
case _:
print("大数字")
try:
num = int(input("输入一个数字:"))
print(f"你输入的是{num}")
except ValueError: # 处理值错误(比如输入字母)
print("输入错误,必须是数字!")
try:
with open("test.txt", "r") as f:
content = f.read()
except FileNotFoundError: # 文件不存在错误
print("文件没找到!")
except PermissionError: # 没有权限访问
print("没有访问权限!")
f = None
try:
f = open("test.txt", "r")
content = f.read()
except FileNotFoundError:
print("文件没找到!")
finally:
if f:
f.close() # 不管有没有异常,都会关闭文件
if True: print("真")
。is_ok = True
if is_ok:
print("状态正常!") # 会执行
if not False: print("不是假")
。is_error = False
if not is_error:
print("没有错误!") # 会执行
==
和 False 比较(None 不等于 False);判断是否为 None 要用is None
。def get_name():
return None # 没有名字时返回None
name = get_name()
if name is None:
print("名字为空!") # 会执行
&
搞混;短路特性:左边为假时,右边不执行。age = 25
is_student = True
if age >= 18 and is_student:
print("成年学生,可以享受优惠!") # 两个条件都满足,执行
|
搞混;短路特性:左边为真时,右边不执行。username = "张三"
email = ""
if username or email: # 只要有一个不为空就可以
print("登录信息有效!") # username不为空,执行
not a and b
相当于(not a) and b
。is_negative = False
if not is_negative:
print("不是负数!") # 会执行
not in
区分。fruits = ["苹果", "香蕉", "橘子"]
if "香蕉" in fruits:
print("有香蕉!") # 会执行
person = {"名字": "张三", "年龄": 20}
if "名字" in person:
print("有名字属性!") # 会执行
==
搞混,==
是值相等,is 是身份相等;对于列表、字典等可变对象,即使值相同,is 也为 False。x = None
if x is None:
print("x是None!") # 会执行
a = 1000
b = 1000
print(a is b) # 可能为False(Python对大整数不缓存,地址不同)
print(a == b) # True(值相等)
:
;函数体要缩进;函数名不能是关键字。def add(a, b):
return a + b # 返回两个数的和
result = add(3, 5)
print(result) # 8
def greet(name, age=18):
print(f"你好,{name},你的年龄是{age}")
greet("张三") # 年龄用默认值18
greet("李四", 20) # 传入年龄20
:
;类名首字母通常大写(约定俗成);方法第一个参数是 self(代表实例本身)。class Student:
def __init__(self, name, age): # 初始化方法
self.name = name # 实例变量
self.age = age
def study(self): # 实例方法
print(f"{self.name}在学习!")
student = Student("张三", 20)
student.study() # 输出:张三在学习!
add = lambda x, y: x + y # 定义加法函数
print(add(3, 5)) # 8
numbers = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled)) # [2, 4, 6, 8]
count = 0
def increment():
count += 1 # 报错!因为没声明global,Python认为这是局部变量,但还没赋值
def outer():
x = 10
def inner():
nonlocal x # 声明使用外层的x
x += 1
print(x)
inner()
outer() # 11(外层的x被修改)
def divide(a, b):
assert b != 0, "除数不能为0!" # 断言b不为0
return a / b
divide(10, 0) # 抛出AssertionError: 除数不能为0!
async
用来定义异步函数,await
用来等待异步操作完成(比如 IO 操作)。await
只能在async
定义的函数内使用;异步函数调用时需要用asyncio.run()
来运行。import asyncio
async def fetch_data():
await asyncio.sleep(1) # 模拟异步IO操作
return "数据获取完成!"
async def main():
result = await fetch_data() # 等待异步函数执行
print(result)
asyncio.run(main()) # 输出:数据获取完成!
with open("test.txt", "w") as f: # 打开文件,f是文件对象
f.write("Hello, World!") # 写入内容,离开with块自动关闭文件
x = 10
del x # 删除变量x,之后再访问x会报错
from module import *
会导入模块所有内容,可能导致命名冲突;导入的是模块中的名称,修改会影响原模块。from math import sqrt # 从math模块导入sqrt函数
print(sqrt(16)) # 4
import math # 导入math模块
print(math.sqrt(25)) # 5(使用模块中的sqrt函数)
import pandas as pd # 取别名pd,方便使用
df = pd.DataFrame() # 创建数据框
def do_nothing():
pass # 占位,否则函数体为空会报错
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder # 返回元组
q, r = divide(10, 3)
print(q, r) # 3 1
def countdown(n):
while n > 0:
yield n # 每次返回n,暂停执行
n -= 1
for num in countdown(5):
print(num) # 依次打印5,4,3,2,1
import module as alias
和with open() as f
。def check_age(age):
if age < 0:
raise ValueError("年龄不能为负数!") # 抛出值错误
print(f"年龄是{age}")
check_age(-5) # 抛出ValueError: 年龄不能为负数!
value = "任意值"
match value:
case _: # 匹配所有情况
print("不管是什么,都执行这里") # 会执行
case (a, *rest):
。numbers = (1, 2, 3, 4, 5)
match numbers:
case (first, *rest): # first是1,rest是[2,3,4,5]
print(f"第一个数是{first},剩下的是{rest}") # 会执行
def handle_value(value):
match value:
case 1:
print("处理1")
case 2:
print("处理2")
case ...: # 其他情况暂时不处理
pass
if = 10
,会报错,因为 if 是关键字,不能用来命名。:
:在 if、else、elif、for、while、def、class、match 等后面,都需要加冒号,新手经常忘记。is
和==
:is
是身份比较(内存地址),==
是值比较,尤其是在判断 None 时,要用is None
,而不是== None
。for item in list: list.append(item)
,会导致循环无限执行,因为列表长度变了。x if condition else y
)。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。