Quine in Python

Hey everyone, this is an interesting tutorial about quine in Python. First, let’s try to understand what is quine.

What is Quine?

Quine is a program that does not take any input and outputs its own source code. In other words, it’s a self-referencing program. We will see how we can write a quine program in Python in this tutorial.

Quine in Python

In this tutorial, we will write a Python quine program using the constructive method. Here’s what we are going to do.

  • Store part of the source code in a variable.
  • Print it in such a way that we don’t even miss the quotes.

And how can we do that?

We will be using eval() and repr() functions in our quine. If you don’t know about these please read these tutorials before you head further.

What eval() does?

This function executes a string of python code that is passed as a parameter. See the below code.

var = "print(5+8)"
eval(var)

Output:

13

What repr() does?

And, this does the following.

print(repr('With the quotes'))

Output:

'With the quotes'

Therefore, we can write our quine like the code given below.

var = "print('var = ', repr(var), 'eval(var)')"
eval(var)

The above code gives the output as:

var = "print('var = ', repr(var), 'eval(var)')" eval(var)

We can create a newline using the below code.

var = "print('var = ', repr(var), '\\neval(var)')"
eval(var)

And now the output is:

var = "print('var = ', repr(var), '\\neval(var)')"
eval(var)

And we’re done here. We can write other quines as well as this.

Shortest Python Quine

The below python is the shortest quine. Run it on your system to get the output the same as the source code given here.

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

Output:

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

 

Note: A program is a quine only if does not take any input at all. The below program gives the same output as the source code but it’s not a quine as it violates the required condition.

print(open(__file__).read())

Output:

print(open(__file__).read())

Leave a Reply