[Tutor] Re: example help

Gregor Lingl glingl at aon.at
Sun Aug 10 01:43:00 EDT 2003


tutor-request at python.org schrieb:

>Today's Topics:
>
>   1. example help (arkamir at softhome.net)
>
>Hey im knew to programing and i got these examples out of the book THE QUICK 
>PYTHON GUIDE. I understand all the other examples but these 2 just stump me. 
>Can anyone help explain them to me?? 
>
>This example gives the factorial of a number 
>
>def fact(n):
>  r=1
>  while n >0:
>     r=r*n
>     n=n-1
>  return r 
>  
>
....

Hi arkamir!

I'd like to show you how you can find for yourself out HOW a program
works. (You'll run into similar situations probably rather often  ... ;-) )

1. Start IDLE
2. Put your fact - function in a python-source file and run it.
3. Now you can calculate for example
 >>> fact(4)
24
 >>>
4. Keep Editor-Window with the fact-source open.
5. Click Menu-Entry Debug-Debugger
- the Debug Control Window appears
- Click check-boxes  Locals and Source (if not already selected)
6. Go back to the Python-Shell-window. Ther now is written:
[DEBUG ON]
 >>>
7. Enter now fact(4) again and type <Enter>
The action of the debugger starts.
Now you should proceed using only the Step-Button. After 2 Clicks
def fact(n):
in the source window should be highlighted and in the lower "locals"-section
of the debugger window you can observe the value of n, namely 4.
 From now on you can execute fact(4) Step by Step.
After two more Steps the statement r =1 will be executed and the actual 
value
of r will be displayed in the "Locals"-section (namely 1).
Proceed Step ba Step and observe the execution of the function line by line
and the corresponding changes of the values of the local variables.
8. Eventually (if the condition n==0 gets True) the statement
    return r
has to be executed. At this moment r has the value 24.
In order not to step into the4 sourcecode of IDLE itself it's wise to Click
Go which finishes the execution of writing fact(4) to the IDLE shell.
24 appears there.

If you like to learn about the execution of functions this way, try it 
our with
your power function and with different arguments.

Regards, Gregor







More information about the Tutor mailing list