24 November 2012

python basics - whitespace and indentations

This might be obvious to some - but I didn't know about indentations.  In Python indentations within a method, have to be the same.  So this will work:

def main():
    print("something to say")
    print("is something to say")

but this won't -
def main():
    print("something to say")
  print("is something to say")

But this will work:
def main():
    print("something to say")
print("is something to say")

The first example does indentation as Python expects within a method.
The second example fails because the indention is not the same.
The third example works, but will first run the line print("is something to say") and then execute the line in the method, if we have the line:
if __name__ == "__main__": main()
This is because the line is at the same level of the method def.  So it's run first.
Either way the third case is valid, as the last print is at the level of the method.

No comments:

Post a Comment