简体   繁体   中英

Commented block indentation in python

Is there a way to avoid "expected indent block" errors in Python without adding pass to a function?

def exclamation(s):
 # s += "!!!"
 # return s

print exclamation("The indented horror")

The above code results in an error on line 5. Yes, remove the comments and the code works fine. However, in debugging stuff I often find myself in a similar situation. Is this just a hang-up of the off-side rule and something I need to get used to or are there ways around this?

There has to be something within your function definition to avoid a SyntaxError .

The issue is that the interpreter will effectively ignore comments during parsing , and so while to a human it might look like something is there, to the parser it is empty.

As jonrsharpe has pointed out in a comment, you can use docstrings to "comment out" your code and have it still work. This is because the docstring is, in effect, a normal string. As such this will be parsed and won't cause a SyntaxError . To take your example code it would look like:

def exclamation(s):
  '''s += "!!!"
  return s'''

# This should print None as nothing is now returned from the func
print(exclamation("The indented horror"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM