Python中文
首页
教程
问答
标签
搜索
登录
注册
Python语法:冒号在行尾时是可选的吗?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我想了解一下,除了空格和注释之外,是否有可能改变Python的语法,使复合语句的冒号成为可选的<em>。例如:</p> <pre class="lang-python prettyprint-override"><code>if so() print("yes") else print("no") </code></pre> <p>这个更改会破坏现有的Python代码吗?会有不明确的结构吗?解析器在诊断某种错误时会变得非常糟糕吗?还有什么我现在想不起来的问题吗</p> <p>当然,我知道冒号使代码更容易阅读的论点。我认为这是有争议的,但我绝对不想在这里讨论意见。我的问题是关于可能的技术问题</p> <p>根据<a href="https://docs.python.org/3/reference/compound_stmts.html" rel="nofollow noreferrer">syntax of compound statements in the documentation</a>,在<code>suite</code>之前总是有一个<code>":"</code>,其中<code>suite</code>被定义为</p> <pre class="lang-none prettyprint-override"><code>suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT </code></pre> <p>以<code>if</code>语句为例</p> <pre class="lang-none prettyprint-override"><code>if_stmt ::= "if" expression ":" suite ("elif" expression ":" suite)* ["else" ":" suite] </code></pre> <p>显然,语法可以这样修改:</p> <pre class="lang-none prettyprint-override"><code>suite ::= ":" stmt_list NEWLINE | [":"] NEWLINE INDENT statement+ DEDENT if_stmt ::= "if" expression suite ("elif" expression suite)* ["else" suite] </code></pre> <p>在<a href="https://github.com/python/cpython/blob/master/Grammar/Grammar#L114" rel="nofollow noreferrer">Grammar file of the CPython source code</a>(也可用<a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow noreferrer">here</a>)中,情况有点不同,在某些构造中,冒号后面的可选<a href="https://www.python.org/dev/peps/pep-0484/#type-comments" rel="nofollow noreferrer">type comment</a>有点复杂,但总的来说,在我看来,应该可以修改与上面类似的语法</p> <p>会有什么技术障碍</p> <hr/> <p>更新:以下可能是<code>suite</code>的<a href="https://en.wikipedia.org/wiki/LL_parser" rel="nofollow noreferrer">LL(1)</a>更友好的语法:</p> <pre class="lang-none prettyprint-override"><code>suite ::= colon_suite | indented_suite colon_suite ::= ":" (stmt_list NEWLINE | indented_suite) indented_suite ::= NEWLINE INDENT statement+ DEDENT </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>由于python条件语句是由缩进分隔的,因此当执行块在新行中以更深的缩进表示时,:将用作冗余标记</p> <p>我不确定这是否适用于同一行语句,您需要一个令牌来将条件与执行语句分开</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
Python中两个字典的交集
5 回答
python中两个字符串上的异或操作数?
2 回答
Python中两个字符串中的类似句子
6 回答
Python中两个字符串之间的Hamming距离
5 回答
python中两个字符串之间的匹配模式
4 回答
python中两个字符串之间的按位或
2 回答
python中两个字符串之间的数据(字节)切片
4 回答
python中两个字符串之间的模式
9 回答
python中两个字符串作为子字符串的区别
6 回答
Python中两个字符串元组的比较
8 回答
Python中两个字符串列表中的公共字符串
7 回答
python中两个字符串的Anagram测试
2 回答
Python中两个字符串的正则匹配
6 回答
python中两个字符串的笛卡尔乘积
3 回答
Python中两个字符串相似性的比较
3 回答
python中两个字符串语义相似度的求法
7 回答
Python中两个字符置换成固定长度的字符串,每个字符的数目相等
7 回答
Python中两个对数方程之间的插值和平滑数据
7 回答
Python中两个对象之间的And/Or运算符
2 回答
python中两个嵌套字典中相似键的和值
8 回答