English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Quine with Python

Quine is a program that does not require input but produces output. It will display its own source code. In addition, Quine has some conditions. We cannot open the source code file within the program.

Example Code

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

Output Result

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

How does this Quine work?

Here is a simple string format. We define a variable 'a', in which we store 'a = %r; print(a %% a)'. Then, we print the value of a and replace %r with the value of a. Therefore, Quine is working.

By opening the file in this way, we can complete the same task.

print(open(__file__).read())

However, in this case, we violate the Quine rule. We cannot open a file in Quine.