【问题标题】:Evaluating a Multiline Code Block (after an `if`) Without Indentation评估没有缩进的多行代码块(在 `if` 之后)
【发布时间】: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


【解决方案1】:

此代码应该工作:

if True:(
x:='hello_x',
print('hello'),
print(x)
)

## hello
## hello_x

在您的情况下,您正在使用 tuple 来破坏 python 的缩进逻辑,因此您需要用逗号分隔每个元素。因为你在tuple,你需要使用Walrus Operator:=来赋值。

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 2019-12-03
    • 2015-09-13
    • 2022-01-19
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多