What does this Python program do?

  • Context: Python 
  • Thread starter Thread starter Demystifier
  • Start date Start date
  • Tags Tags
    Program Python
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 2K views
Messages
14,783
Reaction score
7,430
Can someone tell me what does this Python program do? :wink:
Python:
s = 's = %r\nprint(s%%s)'
print(s%s)

Mentor: add html code tags
 
Last edited by a moderator:
Physics news on Phys.org
Well its printing itself.

Here's an explanation of the %r or repr() function which returns a raw string in python syntax that can be used to recreate the input value.

https://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python

so start with the print statement its going to substitute the string s into the string s at the point of the %s in the string s.

print(s%'a') would produce
Python:
s = 'a'
print(s%s)

The end result is a program that prints itself in proper python syntax so you can run it again. Its kind of a recursive loop except the looping is missing.
 
Last edited:
  • Like
Likes   Reactions: QuantumQuest and Demystifier
This reminds me of the early 1980's story of a kid in school who wrote a program in BASIC that simulated the command prompt and printed fake answers. It responded to 'list' to print a fake program and to 'run' to give a fake answer.

Code:
$ list
10 print 1+1
$ run
3
$ 10 print 1+2
$ run
5
$ list
10 print 1+2
...

The teacher was completely baffled.

I discovered another one online that was truly epic with a fake DOS shell:

http://stevehanov.ca/blog/index.php?id=79
 
Demystifier said:
A program which prints itself is possible in any program language, but it seems that in no other language such a program looks so simple: https://en.wikipedia.org/wiki/Quine_(computing)

Well it works because Python supports printing objects in their literal (source) form. Python isn't the first language to support this. This Lisp example works exactly the same way as the Python version:
Code:
(let ((s "(let ((s ~s))~%  (format t s s))~%"))
  (format t s s))
One of the examples on Rosetta Code uses a reader macro to slightly shorten this (slightly modified here):
Code:
(format t #1="(format t #1=~s #1#)~%" #1#)
 
  • Like
Likes   Reactions: QuantumQuest and Demystifier