-3

This question is coming from this Stack Overflow question. Why is Python is designed to use correct indentation either space or tab? In this way, is it purposefully to serve any benefit?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
anish
  • 6,176
  • 13
  • 67
  • 124
  • 2
    See [Why does Python use indentation for grouping of statements?](https://docs.python.org/2/faq/design.html#why-does-python-use-indentation-for-grouping-of-statements). So basically because Guido thought it was a great idea. One practical reason is that it avoids a whole class of errors, where the code is lying to you: Indentation suggests one thing, but misplaced brackets make the code do a different thing. See [Apple’s #gotofail Security Bug](http://avandeursen.com/2014/02/22/gotofail-security/) for an example. – Lukas Graf Oct 12 '14 at 19:44
  • So [this sort of thing](http://stackoverflow.com/q/26343066/3001761) doesn't happen. – jonrsharpe Oct 13 '14 at 15:21

2 Answers2

3

Indentation is essential in Python; it replaces curly braces, semi-colons, etc. in C-like syntax.

Consider this code snippet, for example:

def f(x):
    if x == 0:
        print("x is zero")
        print("where am i?")

If it weren't for indentation, we would have no way of indicating what code block the second print statement belongs to. Is it under the if statement, the function f or just by itself in the document?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
dramzy
  • 1,369
  • 1
  • 11
  • 23
2

There is no set width of a tab character, so Python has no way of knowing how many spaces to count a tab as.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
  • 3
    Not entirely true. Python has a [precise definition](https://docs.python.org/2/reference/lexical_analysis.html#indentation) of how a tab is to be interpreted as a sequence of spaces. In practice, correctly mixed spaces and tabs are unlikely to *look* correct, which is why one is strongly encouraged to pick either tabs or (preferably) spaces and stick with that. – chepner Oct 12 '14 at 21:47