tur*_*too 12 python conditional comments multiline python-3.x
我想要一个多行if语句,例如:
if CONDITION1 or\
CONDITION2 or\
CONDITION3:
Run Code Online (Sandbox Code Playgroud)
我想评论每行源代码的结尾
if CONDITION1 or\ #condition1 is really cool
CONDITION2 or\ #be careful of condition2!
CONDITION3: #see document A sec. B for info
Run Code Online (Sandbox Code Playgroud)
我被禁止这样做,因为python将它全部视为一行代码和报告SyntaxError: unexpected character after line continuation character.
我应该如何实施和记录冗长的多行if语句?
Mar*_*ers 17
不要使用\,使用括号:
if (CONDITION1 or
CONDITION2 or
CONDITION3):
Run Code Online (Sandbox Code Playgroud)
并且您可以随意添加评论:
if (CONDITION1 or # condition1 is really cool
CONDITION2 or # be careful of conditon2!
CONDITION3): # see document A sec. B for info
Run Code Online (Sandbox Code Playgroud)
Python允许在带括号的表达式中使用换行符,并且在使用注释时,只要涉及表达式,就会将新行视为位于注释开始之前.
演示:
>>> CONDITION1 = CONDITION2 = CONDITION3 = True
>>> if (CONDITION1 or # condition1 is really cool
... CONDITION2 or # be careful of conditon2!
... CONDITION3): # see document A sec. B for info
... print('Yeah!')
...
Yeah!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2196 次 |
| 最近记录: |