0

I see that python definition, if statements end in a colon like below

def myFunc():
  pass

if x == "x":

class myClass(object):

I am curious why we even need to type this colon when indentation is at our rescue? I am finding the use of colon redundant here.

YOU
  • 120,166
  • 34
  • 186
  • 219
  • 1
    because you can sometimes write those in one line, python won't make semicolon optional for less benefit. – YOU May 15 '16 at 01:37
  • I guess the interpreter looks for these colons to add one level of indentation. – romain-aga May 15 '16 at 01:37
  • That's an interesting question. Off the top of my head, I don't see why the normal continuation rules wouldn't be sufficient here. In a world without colons, then if you wanted a one-liner if statement you would use a semicolon (on par with how you combine other statements). Else \n would suffice (modulo other rules around parens etc.). – AnilRedshift May 15 '16 at 01:38
  • I suspect @romain-aga is onto something. It is perhaps possible that the language itself doesn't strictly need colons to figure out what to do, but it is for humans to know they have to indent the next line(s) – AnilRedshift May 15 '16 at 01:40
  • 1
    http://stackoverflow.com/questions/215581/what-is-the-purpose-of-the-colon-before-a-block-in-python – Pythonista May 15 '16 at 01:42
  • Natural languages have redundancy, such as matching number for verb-object agreement in English. This is useful if you have a noisy channel. Not so clear when you have a simple text file, but the redundancy does help with error reporting. Note that if you follow this logic too far, you end up programming directly in the abstract syntax tree, and everything you write is lisp. – Neapolitan May 15 '16 at 01:44

0 Answers0