[Tutor] Need to write a python and call it within a python mainprogram (fwd)
Alan Gauld
alan.gauld at freenet.co.uk
Sat Feb 18 23:49:07 CET 2006
> I know how to write functions in Fortran.
>
> Please help me with the syntax. I don't know how to tell python to run a
> main program and use subroutines.
OK, Now we have some specifics.
First to make a program run just create a text file and use an
extension of .py, for example myprogram.py (You can use
File->New from IDLE if you like)
Then from the operating system command line type
C:\> python myprogram.py
(Assuming you are on Windows - tell us if you are on
MacOS or Linux or something else...)
To define a function called f that takes a parameter of x
in python use the following syntax:
def f(x):
return x**2
Note the colon at the end of the definition, that starts a
code block. (And was why you got the error in your
if statement - no colon
Note the indented block of code in the function body.
Both are essential.
To call the function f with an argument of 4
result = f(4)
> I don't know how to make those subroutines available to
> the main program.
Put them in the same file in the first instance.
Alternatively you could put them in another file called say
myfuncs.py. Then in myprog.py import the myfuncs "module"
import myfuncs # note no .py
result = myfuncs.f(3)
Note the use of the module name in font of the function name.
Try going through the tutorials, they should answer the
rest of your questions but if you get stuck come back to
us with any specifics
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
currently broken! :-(
More information about the Tutor
mailing list