【发布时间】:2022-12-02 22:06:37
【问题描述】:
是否可以让 Python3 将未缩进的代码块视为代码块?如果是这样怎么办?
这更多是出于对 Python 工作原理的好奇。通常如果你想在 if 语句之后运行代码块,你需要缩进下面的内容:
if True:
x = 'hello'
print(x)
## hello
有没有办法使用if而不缩进接下来的两行?
如果下一行是函数调用(而不是赋值)并且用括号将其括起来,则可以让它工作,如下所示:
if True:(
print('hello')
)
## hello
但是,如果您添加多行或作业,它就无法工作:
if True:(
print('hello')
print('hello2')
)
## File "<stdin>", line 3
## print('hello2')
## ^
## SyntaxError: invalid syntax
## >>> )
## File "<stdin>", line 1
## )
## ^
## SyntaxError: unmatched ')'
if True:(
x = 'hello'
)
## File "<stdin>", line 2
## x = 'hello'
## ^
## SyntaxError: invalid syntax
## >>> )
## File "<stdin>", line 1
## )
## ^
## SyntaxError: unmatched ')'
有没有办法在不缩进的情况下评估if 之后的多行?也许类似于我用于简单的 print('hello) 的括号技巧,但它适用于多行和作业?
【问题讨论】:
-
Python 基本上可以使用缩进,这是基础,所以没有。
标签: python python-3.x