gpt4 book ai didi

python - 内联 if 语句的允许语法

转载 作者:行者123 更新时间:2023-11-28 21:22:03 30 4
gpt4 key购买 nike

有时我喜欢滥用 python 语法,特别是短的 if block :

if True : print 'Hello'
else : print 'Bye'

现在我尝试对函数定义做同样的事情:

if True : def a(): return 'a'
else : def a(): return 'b'
print a()

但令人惊讶的是我不能那样做:

  File "xxx.py", line 1
if True : def a(): return 'a'
^
SyntaxError: invalid syntax

以下(相当于我,但不适合 python)版本就可以了:

if True :
def a(): return 'a'
else :
def a(): return 'b'
print a()

为什么?关于我可以在 if 语句中内联什么似乎有一个规则。也许在 if 冒号之后不允许冒号?这个规则在哪里指定的?或者也许我违反了更一般的规则?哪个?

最佳答案

你可以在这里看到if的语法http://docs.python.org/2/reference/compound_stmts.html#if

根据语法if允许

"if" expression ":" suite

suite定义为

suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT

stmt_list 定义为

stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

语句定义为

stmt_list NEWLINE | compound_stmt

compound_stmt 定义为

compound_stmt ::=  if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| decorated

我们看到 funcdefcompound_stmt 之一。所以,在 if 条件下,如果我们必须定义一个函数,def 必须有一个 NEWLINEINDENT 在那之前。这就是为什么您尝试的无效。

但是这种简单又好用的方法怎么样

def a():
return "a" if True else "b"

关于python - 内联 if 语句的允许语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20017106/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com