我可以使用“as”吗? if语句中的机制 [英] Can I use the "as" mechanism in an if statement
问题描述
是否可以在中使用
语句如作为
,如果 with
我们使用,例如:
Is it possible to use as
in if
statement like with
that we use, for example:
with open("/tmp/foo", "r") as ofile:
# do_something_with_ofile
这是我的代码:
def my_list(rtrn_lst=True):
if rtrn_lst:
return [12, 14, 15]
return []
if my_list():
print(my_list()[2] * mylist()[0] / mylist()[1])
我可以在此类型中使用 if
:
Can I use if
in this type:
if my_list() as lst:
print(lst[2] * lst[0] / lst[1])
在第一个如果
我打电话给 my_list
四次。我可以使用变量,但我想知道有没有办法使用作为
?
In first if
I called my_list
four times. I can use a variable but I want to know is there any way to use as
?
推荐答案
没有。 if
语句定义为:
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
...其中 test
是一套测试表达式与or和and结合。
... where test
is a suite of test expression combined with or/and.
更多信息,请参阅: http://docs.python.org/3.3/reference/grammar.html
您可以先定义变量,然后测试其值:
You can defined your variable before and then test its value:
lst = my_list()
if lst:
print(lst[2] * lst[0] / lst[1])
如果你想要一些挑战(仅限于过期的东西),你可以改变Python语法,玩得开心: http://www.python.org/dev/peps/pep-0306/
If you want some challenge (and for expiremental stuff only), you can change the Python grammar, have fun: http://www.python.org/dev/peps/pep-0306/
这篇关于我可以使用“as”吗? if语句中的机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!