Quine in Python


The Quine is a program, which takes no input, but it produces output. It will show its own source code. Additionally, Quine has some conditions. We cannot open the source code file inside the program.

Example 1

Here a simple string formatting is working. We are defining a variable ‘a’, and inside a, we are storing ‘a=%r;print (a%%a)’ Then we are printing the value of a, and also replacing %r with the value of a. Thus the quine is working −

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

Output

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

Example 2

We defined a variable _ and assigned ‘_=%r;print _%%_’. Then, we printed _%_. Wwe are printing _ with _ as input to string formatting. Therefore, %r in _ gets the value of _.

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

Output

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

Not a Quine

The below code may look the smallest Quine in comparison with the above two example. But, it is actually not a quine because we are violating the rule of Quine. We cannot open a file in Quine.

Example

print(open(__file__).read())

Updated on: 12-Aug-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements