Far*_*dix 5 python if-statement
是否可以as在我们使用的if语句with中使用,例如:
with open("/tmp/foo", "r") as ofile:
# do_something_with_ofile
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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])
Run Code Online (Sandbox Code Playgroud)
我可以if在这种类型中使用:
if my_list() as lst:
print(lst[2] * lst[0] / lst[1])
Run Code Online (Sandbox Code Playgroud)
首先if我打了my_list四次电话.我可以使用变量,但我想知道有什么方法可以使用as吗?
否。该if声明的定义为:
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
Run Code Online (Sandbox Code Playgroud)
...其中test是一组与 or/and 组合的测试表达式。
有关更多信息,请参阅:http://docs.python.org/3.3/reference/grammar.html
您可以之前定义变量,然后测试其值:
lst = my_list()
if lst:
print(lst[2] * lst[0] / lst[1])
Run Code Online (Sandbox Code Playgroud)
如果你想要一些挑战(仅限过期的东西),你可以改变Python语法,玩得开心:http ://www.python.org/dev/peps/pep-0306/