posted by Dinesh
on Tue, 09/22/2009 - 15:17
While working on Python you might have witnessed a Eureka moment. Please post it here to share it with the class.
Forums:
- Log in to post comments
While working on Python you might have witnessed a Eureka moment. Please post it here to share it with the class.
A mysterious function
Look at the following function : def mystery(x): if x == 1: return 1 result = x * mystery(x-1) return result z = mystery(5) print "Result = %d" % z raw_input() Can you guess what it does? Check it out.Recursion
The above function is an example of what is called Recursion. Here the function calls itself.
For example if you call mystery(5) it will execute this way:
Inside mystery
x == 5 thus ("if" conditions fails and we move to next statement.)
result = 5 * mystery (4)
i.e. it calls mystery(4) which executes like:
x == 4 thus
result = 4 * mystery(3)
and so on until mystery(1) is called as in that case
x == 1 so mystery(1) returns 1.
To conclude,
mystery(5) = 5 * mystery(4) = 5 * 4 * mystery(3) = 5 * 4 * 3 * mystery(2) = 5 * 4 * 3 * 2 * mystery(1) = 5 * 4 * 3 * 2 * 1 = 120
Use of \ (escape sequence) in a print statement
We know that escape sequences are treated specially by Python. With reference to the question in Quiz2 check this out:
print "Let me stamp \No Alcohol\.."
should it work? Well it does work.
Now try:
print "Let me stamp \No Alcohol\"
This one doesn't work, why?
The reason is that when you have \" in your print statement it tells Python that this double quote is not to be treated as the closing double quote instead just print it as any other character. So we do not get the mate of the first double quote which starts at ("Let) and hence the statement looks something like:
>>>print "Here is a similar statement
That's why there is an error.