logo

Quine i Python

Quine är ett program som inte tar någon input utan matar ut en kopia av sin egen kod. Vi har diskuterat kin i C . The shortest possible quine in python is just a single line of code! Python
_='_=%r;print _%%_';print _%_ 
In case of Python3.x Python
_='_=%r;print (_%%_)';print (_%_) 
Förklaring: Ovanstående kod är en klassisk användning av strängformatering. Först definierar vi en variabel _ och tilldela den '_=%r;print _%%_'. För det andra trycker vi _%_ . Här skriver vi ut _ med _ som input till strängformatering. Så %r i _ får värdet av _. Du kan till och med använda %s i stället för %r . Vi använde dubbelt % i '_=%r;skriv ut _%%_' för att escape % . But you may say that the below code is the smallest right! Python
print open(__file__).read() 
You need to note that it is indeed the smallest python program that can print its own source code but it is not a quine because a quine should not use öppna() funktion för att skriva ut källkoden.