Posted on Leave a comment

Python One Line Quine

Most computer scientists, programmers, and hackers don’t even know the meaning of the word “Quine” in the context of programming. So, first things first:

What is a Quine?

Roughly speaking, a quine is a self-reproducing program: if you run it, it generates itself.

Here’s a great definition:

:quine: /kwi:n/ /n./ [from the name of the logician Willard van Orman Quine, via Douglas Hofstadter] A program that generates a copy of its own source text as its complete output. Devising the shortest possible quine in some given programming language is a common hackish amusement. (source)

The name “quine” was coined by Douglas Hofstadter, in his popular science book Gödel, Escher, Bach, in honor of philosopher Willard Van Orman Quine (1908–2000), who made an extensive study of indirect self-reference, and in particular for the following paradox-producing expression, known as Quine’s paradox.

Wikipedia

The shortest possible quine is the following empty program:

 

The program is self-reproducing because the output of the program is the program itself. Go ahead and run it in your own shell! 😉

Let’s dive into a collection of Python Quines to demonstrate how they work!

Python One-Liner Quine 1

Here’s a short one-liner Quine, I found at this resource:

s='s=%r;print(s%%s,sep="")';print(s%s,sep="")

Here’s the code in an interactive shell so that you can play with this Quine in your browser:

Exercise: Run the code. What’s the output? Can you explain why?

Python One-Liner Quine 2

Leave a Reply