3
_='_=%r;print (_%%_) ';print (_%_)

(Edit: I have recieved your input and fixed the code, thanks for the correction.)

This is the shortest quine you can write in Python (I'm told). A quine being code that returns itself.

Can someone explain this line of code to me as if I know nothing about Python? I use Python 3.x by the way.

What I'm looking for is a character-by-character explanation of what's going on.

Thanks.

Endvisible
  • 79
  • 6
  • Not seriously: the shortest quine should be an empty text file. – knh190 Mar 30 '19 at 09:56
  • How is that not a quine? It is a program that prints it's own source code. – Dan D. Mar 30 '19 at 10:44
  • @DanD.: Run it. Compare the output to the source code. It doesn't match. – user2357112 Mar 30 '19 at 10:44
  • The correct quine is `_='_=%r;print (_%%_) ';print (_%_)` – sanyassh Mar 30 '19 at 10:44
  • @user2357112 Friend, dear friend, I'm not an expert by any means. I know how string literals work, but I've never seen something this compressed (seeing as most people want readability (see PEP 8)). I was simply confused as to how this worked, and I'm still learning. – Endvisible Mar 31 '19 at 17:06
  • Using www.thonny.org to step through `_='_=%r;print (_%%_) ';print (_%_)` is a good exercise and highlights thonny's educational power. – joseville Nov 03 '21 at 00:05
  • Do note the shortest quine in python is actually 1 byte shorter than this – DialFrost Jan 05 '23 at 23:17

1 Answers1

6

As pointed out in the comments, the correct quine is _='_=%r;print (_%%_) ';print (_%_), using this, let's begin:

The ; executes to commands in a line, so the following:

_='_=%r;print (_%%_) ';print (_%_)

is equivalent to:

_='_=%r;print (_%%_) '
print (_%_)

In the first line, _ is a valid variable name which is assigned the string '_=%r;print (_%%_) '

Using python's string formatting, we can inject variable into strings in a printf fashion:

>>> name = 'GNU'
>>> print('%s is Not Unix'%name)

GNU is Not Unix

>>> print('%r is Not Unix'%name)

'GNU' is Not Unix

%s uses a string, %r uses any object and converts the object to a representation through the repr() function.

Now imagine you want to print a % as well; a string such as GNU is Not Unix %. If you try the following,

>>> print('%s is Not Unix %'%name)

You will end up with a ValueError, so you would have to escape the % with another %:

>>> print('%s is Not Unix %%'%name)

GNU is Not Unix %

Back to the original code, when you use _%_, you are actually substituting the %r in the _='_=%r;print (_%%_) with itself and the %% would result in a % because the first one is treated as escape character and finally you are printing the whole result, so you would end up with:

_='_=%r;print (_%%_) ';print (_%_)

which is the exact replica of what produced it in the first place i.e. a quine.

Amen
  • 1,524
  • 5
  • 22
  • 41