Curiosity: indentation in python is in fact optional? :)

Hi,
I just realized that the indentation in python is in fact optional?!

Forget for a moment that it is less readable, just for the sake of curiosity, these code snippets are fully working!

# while loop:
n = 0;
while n < 5: print(n); n += 1;
# for loop:
g = 0
for n in range(5): print(n,g); g+=1;
# if / else statement when condition is true.
if True: print('hello'); print(' world')
else: print('else'); print(' statement');
# if / else statement when condition is false.
if False: print('hello'); print(' world');
else: print('else'); print(' statement');

and even functions:

# function:
def my_func(): print('hello'); print(' world'); return 'successful!';
my_func();

:man_shrugging:

1 Like

How would you determine when the code snippet ends in a longer code script vs ~3/4 line code snippets?

The compound statements (while, for, if, etc.) , after the colon :, have a suite, which is defined as

suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT

So, there is the option of a statement list (simple statements separated by semi-colon) or go to a new line, but add indentation.

4 Likes

I think you may have misstated the situation. Indentation is not optional, it is required if the block (suite) spans multiple lines. If you are willing to put each block on a single line, then indentation is not relevant.

1 Like

Interesting observation. You could also use backslashes for line continuation to make it even more horrible:

def my_func(): \
print('hello', end=""); \
print(' world'); \
return 'successful!';
n = 0;
while n < 5: \
print(n) if n % 2 else None; \
n += 1;
my_func();

But you can’t have more than one level of structure, which is a bit limiting. So you can’t have if statements inside functions, for example, although you can use if expressions instead in some cases:

def fizzbuzz(n): \
print("fizzbuzz") if n % 15 == 0 \
else print("fizz") if n % 3 == 0 \
else print("buzz") if n % 5 == 0 \
else print(n)
i = 1
while i < 20: \
fizzbuzz(i); \
i += 1
6 Likes

There are limitations to this, and there are ways to work around the limitations. None of this should be particularly new or interesting to experienced Pythonistas (unless they’re so disciplined that they’ve never even thought about writing ugly, complex code).

5 Likes

thank you all for the comments!

from the StackOverflow link above - there is an interesting point that one cannot have more then one : in a line.

So this code is not valid and doesn’t work:

def my_func(): i=1; while i < 5: i += 1;

Anyway, if one needs to write in one line, there is a workaround: an answer suggests to use exec().
So this code works fine:

exec('def my_func(): \n\t i=1; \n\t while i < 5: \n\t\t print(i) \n\t\t i += 1;')
my_func()

:+1:

Writing a Python program without indentation is like writing a novel without the letter “e”. It’s possible, but other than as a fun challenge, not particularly useful.

7 Likes

Like the novel, Gadsby, which is a lipogram that avoids words with the letter “e”, the primary value of a Python program that avoids indentation would be its status as a novelty. :wink:

See:

3 Likes

Exactly what I was obliquely referring to :slight_smile:

2 Likes
  1. Yes I’ve used the semi-colon to separate statements if I run a short Python program from the CLI.
  2. But how do we know this semi-colon will work in this context in 10 years?

I just follow what the tutorials show and use indentation. The indentation also makes the code easier to read. I never liked the old 1980 BASIC language where we had to put multiple statements on one line to save memory. (Like the VIC-20.)

It is interesting though.

EDIT: I ended up using semi-colons in my .pdbrc file to make some debugger aliases.

# alias dir import glob; myfiles = glob.glob("%1"); for i in myfiles: print(i)
alias dir import glob; print(glob.glob("%1"))
alias dir1 import glob; _ = [print('-', x) for x in sorted(glob.glob("%1"))]
alias q quit()

So it does work there also. I wouldn’t now how to make an alias with multiple lines.

1 Like

It will. :slight_smile:

1 Like

Yes, I thought so.

Actually, this genre of Python programming deserves even more credit than that. Like other forms of art that work with constraints, it has potential educational value. Working with imposed constraints or prescribed patterns encourages creativity and research. After all, many forms of poetry have a long cherished tradition.

For just a few of many examples of creativity in programming and writing that involve adhering to selected constraints and patterns, see the following Wikipedia articles:

Such a strategy extends to the visual arts, as well. For example, one can work with a minimal palette of colors, or resort to using only dots to create a picture.

2 Likes

Apologies, but you’ve triggered my rant card.

Once upon a time, there was a breaking change to the language’s syntax. It was very clearly a good idea that enabled a lot of powerful new idioms. It was bundled with a bunch of other very good ideas, including one that straightened out the language semantics so that using an established standard (already existing for 17 years at release, and supported in some form in the language for 8) wouldn’t be a hack, completely eliminating two entire subclasses of confusing errors (whereby the language would tell you that there was a problem with doing the opposite of what you’d explicitly told it to do). Then there was the idea that maybe beginners shouldn’t learn how to create an arbitrary code execution exploit in their program on day 1.

But many of these ideas (including the ones described above) were not backwards compatible.

Anyway, people were given huge amounts of advance warning about this syntax change. There was a whole new series of PEPs starting two and a half years before the eventual release - and discussion even before that. They got a tool to preview the new syntax by itself (and some people were apparently surprised that the tool did exactly what it was designed to do). They also got a tool in the standard library to help with the migration. (By the way, that tool preserves the arbitrary code execution exploit. Because, you know, backwards compatibility.) But then two years later they got an additional update (not just a patch) for the old way of doing things, with an extended maintenance schedule and a bunch of the new stuff (where it didn’t break backwards compatibility) getting backported. Three years after that they had to be explicitly told that there wouldn’t be another one and the language had not simply been forked completely.

All in all, from the first release of the first Python supporting the new way, until the last release of the last Python supporting the old way, was about 13 and a half years. And people still loudly complained the entire time (in one famous case, a well-known Python educator made some absolutely bizarre and unsound arguments that were then thoroughly refuted), missed their migration deadlines, and kept asking the community to help with unofficial support after that. Another 4 years beyond that, we’re finally at the point where I scarcely hear about the old version any more. That migration tool in the standard library still won’t be removed for a few months yet (and Python versions including it will, of course, be supported for up to another 4 years).

So, no, Python won’t drop support for semicolons any time soon. It would break huge amounts of existing code for a purely aesthetic principle. And everyone remembers far too well how difficult it is to get certain segments of developers on board with that.

4 Likes