[Tutor] help

Jeff Shannon jeff@ccvcorp.com
Tue Jul 29 17:53:01 2003


Thomas Clive Richards wrote:

>>how can i sort out my problem? what am i doing wrong? is it because i
>>press enter?
>>    
>>
>
>Hi,
>
>python has a command line interpreter, which sounds like what you're
>using. If you want to run all the commands at once, create a text file
>and give it a .py extension. in this file, write your program. Note that
>under windows, it's a good idea to put "timport time" at the top , and
>"time.sleep(10)" at the bottom. This will cause the output window to
>remain open for 10 seconds after the program has finished running.
>  
>

Another (probably preferable) way to accomplish that is to simply add 
this line to the end of the program:

raw_input("Press Enter to end this program.")

raw_input() will wait for something to be entered, i.e. for the return 
key to be pressed.  We don't really care at this point what's typed, 
just so long as the program waits until *something* has been done to end 
it, so this works pretty well.  

The O.P.'s problem can also be solved within the interactive 
interpreter, though.  The trick is to put the sequence of things that 
you want to do inside a function, using the def keyword --

 >>> def show_area():
...     width = input("Enter width: ")
...     length = input("Enter length: ")
...     area = width * length
...     print "The area is:", area
...    
 >>>

Now you can call show_area() as a shorthand for all of those commands at 
once, like so:

 >>> show_area()
Enter width:  5
Enter length:  8
The area is: 40
 >>>

Even if you do put your code in a separate file (which you'd need to do 
if you want to save it and run it at a later date), it's a very good 
idea to put everything into functions like this.  By separating your 
program into small pieces, it becomes a lot easier to understand what's 
going on in each part, which makes it easier to understand what's 
happening overall too.

Jeff Shannon
Technician/Programmer
Credit International