won't recognize functions in script
Jeff Shannon
jeff at ccvcorp.com
Fri May 10 18:50:14 EDT 2002
In article <3cd9958d at news.cc.umr.edu>, Carl says...
> ... When I define
> functions python gives me 'NameError: name 'ascii_val' is not defined'
>
> this piece of my code is this:
>
>
> print ch, ascii_val(ch) # ch is just a character read from a file
>
> def ascii_val(char):
> # returns 1-26 for A-Z or 27 for a space
[...]
Functions must be defined before they are executed. The snippet
you posted will try to call ascii_val() before the interpreter
has seen the 'def ascii_val(char)...' block. That's where your
name error is coming from.
Note that the def must come before the attempt to *execute* the
function. You can refer to ascii_val() within another function
def, before it is defined, as long as that second function is not
executed before the interpreter has processed ascii_val()'s def.
So, for example, this will work:
def print_ascii(mystring):
for ch in mystring:
print ch, ascii_val(ch)
def ascii_val(char):
# ... (as defined above)
print_ascii("testing")
As a side note, you might wish to rename your function, because
it's not returning an ascii value -- the ascii value is what is
returned from ord(char), and then you're massaging that into
something else. Picking accurately descriptive function names
will make your code *much* less confusing later on... :)
--
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list