You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中range()函数调用与match模式匹配的参数要求差异原因咨询

Python中range()函数调用与match模式匹配的参数要求差异原因咨询

嘿,这个关于range()的参数差异问题确实挺容易让人困惑的,我先把实际测试的情况给你理清楚——所有测试都是在Windows 10系统下用Python 3.13.2完成的:

一、直接调用range():只能用位置参数

当我们直接调用range()函数的时候,只能传位置参数,如果尝试用关键字参数,立刻就会抛出TypeError:

>>> range(2, 5)
range(2, 5)
>>> range(start=2, stop=5)
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    range(start=2, stop=5)
    ~~~~~^^^^^^^^^^^^^^^^^
TypeError: range() takes no keyword arguments

二、match模式匹配range():必须用关键字参数

反过来,在match语句里匹配range对象的时候,不能用位置参数,必须指定关键字参数才能成功匹配,否则同样会报错:

>>> match range(2, 5):
...     case range(0, y, 1):
...         print('1 argument')
...     case range(x, y, 1):
...         print('2 arguments')
...     case range(x, y, z):
...         print('3 arguments')
...     case _:
...         print('none of the above')
...
Traceback (most recent call last):
  File "<python-input-0>", line 2, in <module>
    case range(0, y, 1):
         ~~~~~^^^^^^^^^
TypeError: range() accepts 0 positional sub-patterns (3 given)

而改用关键字参数之后,就能正常匹配并输出结果了:

>>> match range(2, 5):
...     case range(start=0, stop=y, step=1):
...         print('1 argument')
...     case range(start=x, stop=y, step=1):
...         print('2 arguments')
...     case range(start=x, stop=y, step=z):
...         print('3 arguments')
...     case _:
...         print('none of the above')
...
2 arguments

三、匹配时的关键字参数不能随便命名

更有意思的是,这里的关键字参数不能瞎起名,必须是start、stop、step这三个固定的名字,不然匹配会直接失败,而且不会抛出异常:

>>> match range(2, 5):
...     case range(aaa=0, bbb=y, ccc=1):
...         print('1 argument')
...     case range(aaa=x, bbb=y, ccc=1):
...         print('2 arguments')
...     case range(aaa=x, bbb=y, ccc=z):
...         print('3 arguments')
...     case _:
...         print('none of the above')
...
none of the above

备注:内容来源于stack exchange,提问作者Qba23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 09:28:08