0

I was playing some code golf and came across behavior I don't understand.

Why is the following code valid:

import os; print(1)

and this code is valid:

import os
for i in range(10): print(1)

but not:

import os; for i in range(10): print(1)

It errors out with:

File "<stdin>", line 1
    import os; for i in range(10): print(1)
               ^^^
SyntaxError: invalid syntax

It breaks my mental model of how the semicolon works in python, shouldn't this be valid? If not, could someone explain why? Is there something special about the for and while keywords that prohibit oneliners?

What's a work around for playing code golf using python?

npengra317
  • 126
  • 2
  • 7
  • Note that Stack Overflow is limited to _practical_, answerable questions. We explicitly disallow codegolf -- kicked it out to [codegolf.se] Stack Exchange probably the better part of 15 years ago now. – Charles Duffy May 09 '23 at 20:15

1 Answers1

1

Sorry, but there's no workaround for indentation in some cases. As a general rule when golfing you can't have a ; and a : that introduces a new block (like if, for, while, def, try etc.) in the same line. Take it as one of the drawbacks of using Python as a golfing language.

That said, there can be other ways to get around it using some tricks which you acquire with practice. For example,

import os
for i in range(10):
    print(1)

can be rewritten as

import os;[print(1)for _ in' '*10]

(works as of py3.11)

ificiana
  • 98
  • 7