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 ?

<div class="execute"></div><div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;">a<span class="token operator">=</span><span class="token string">'a=%r;print (a%%a)'</span><span class="token punctuation">;</span><span class="token keyword">print</span> <span class="token punctuation">(</span>a<span class="token operator">%</span>a<span class="token punctuation">)</span>
</div><div class="output-wrapper"><div class="console-close"></div><div class="code-output"></div></div>

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 _.

<div class="execute"></div><div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;">_<span class="token operator">=</span><span class="token string">'_=%r;print (_%%_)'</span><span class="token punctuation">;</span><span class="token keyword">print</span> <span class="token punctuation">(</span>_<span class="token operator">%</span>_<span class="token punctuation">)</span>
</div><div class="output-wrapper"><div class="console-close"></div><div class="code-output"></div></div>

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: 2022-08-12T12:17:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements