My method is being recognized within my own program. Newbie mistake probably

Here's my code:

sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ")
words = sentenceToTranslate.split(" ")

for word in words:
    if isVowel(word[0]):
        print "TEST"


def isVowel(letter):
    if letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter.lower() == "o" or letter.lower() == "u":
        return True
    else:
        return False

The error I get is:

NameError: name 'isVowel' is not defined

What am I doing wrong?


Asked by: Max656 | Posted: 06-12-2021






Answer 1

The function hasn't been defined yet, so the name 'isVowel' doesn't have a function bound to it: that only happens at the time when you say "def".

Solution: move your code below the def isVowel(letter).

Answered by: Blake569 | Posted: 07-01-2022



Answer 2

Put the def isVowel definition at top.

You defined the function after it had already been called. Since, the source code is not compiled and interpreted at run-time, it does not check for this error.

Also, you can redefine the function as

def isVowel(letter):
    if letter.lower() in "aeiou":
        return True
    else:
        return False

Answered by: Sam899 | Posted: 07-01-2022



Answer 3

At the risk of being downvoted again, here is some further insight into these "define before use" requirements.

Note that the body of a function is not processed for the existence of symbols in until that function gets called. So you could write code like this:

def A():
    # calls B - even though B is defined later in the module
    B()

def B():
    # calls A
    A()

And this works just fine. The interpreter/compiler works top-down through the module, but when it sees a function or class definition, it processes the definition of the function, but not the function itself.

The reason your code failed was because the reference to isVowel was not within a function, but was at module scope. Code in the module that is not within a function is executed immediately, so the interpreter needs to be able to resolve any names based on what it has seen so far.

Answered by: Aida545 | Posted: 07-01-2022



Answer 4

Python executes all the statements that you put in your module when it encounters them, from top to bottom. What happens is that you try to call isVowel before you have defined that function. The python interpreter has not reached that code yet.

If you put the definition of isVowel at the top of your file you will be able to call it.

Answered by: Owen459 | Posted: 07-01-2022



Answer 5

I think you need to define the function first, then call it after it has been defined.

def isVowel(letter):
    if letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter.lower() == "o" or letter.lower() == "u":
        return True
    else:
        return False

sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ")
words = sentenceToTranslate.split(" ")

for word in words:
    if isVowel(word[0]):
        print "TEST"

Often you will put the function definitions in another file, and import them to avoid these problems.

Answered by: Brad367 | Posted: 07-01-2022



Answer 6

Here are a couple of other points to make for a newbie Pythoner:

1) What is the point of writing this?

def isVowel():
    if boolean-expression:
        return True
    else:
        return False

You already have the True/False-ness captured in the value of the boolean expression, just:

def isVowel():
    return boolean-expression

2) Function calls are performance killers. Especially when you have such a limited set of items to check for, instead of calling .lower() so that you can check against "aeiou", check the character itself against both the lower and upper case letters, "aeiouAEIOU". Even though this is twice the length string to test for membership, it saves us the call to the lower() function.

Here are some performance test results:

import time
import string
time.clock()

reps = 100000
testString = (string.uppercase + string.lowercase) * reps

start = time.clock()
for c in testString:
    answer = c.lower() in "aeiou"
end = time.clock()
print end-start

start = time.clock()
for c in testString:
    answer = c in "aeiouAEIOU"
end = time.clock()
print end-start

start = time.clock()
for c in testString:
    pass
end = time.clock()

Prints:

3.27782246068
1.76839123408
0.713913919227

The third loop shows the time it takes just to iterate over the testString itself, so the time spent in the body of the loop (assuming pass takes negligible time) is:

2.563908541
1.054477315

By avoiding the lower() call, the second technique is more than twice as fast.

Answered by: Maddie242 | Posted: 07-01-2022



Similar questions

python - Can anyone help me with this? "The term 'scrapy' is not recognized as a cmdlet name, function, script file or operable program."

PS C: \ Users \ Acer \ projects \ worldometers \ worldometers> conda activate virtual_workspace PS C: \ Users \ Acer \ projects \ worldometers \ worldometers> scrapy crawl countries scrapy: The term 'scrapy' is not recognized as a cmdlet name, function, script file or operable program. Check the spelling of the name or, if a path has been included, see if the path is correct and try again. In line: 1 character: 1 + scrapy ...


python - Why would an "command not recognized" error occur only when a window is populated?

My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it. However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows...


python - Django custom auth backend not recognized on Apache

I'm trying to deploy my Django application to an Apache2 based server with mod_python. I've set the handlers right and made the configuration to make mod_python work with my project. My project implements a custom auth backend to connect my users to twitter, and my backend implementation is on: myproject |- backends/ directory.Everything seems to be working fine, my pages load and I can ma...


Trying to use py2exe, but python is not recognized

I am following the the tutorial at http://www.py2exe.org/index.cgi/Tutorial to figure out how to use py2exe. I get down to step 3 where you are supposed to run the command: python setup.py py2exe I do that and then I get this error: 'python' is not recognized as an internal or external command,...


python - How to have recognized all the libraries Rpy2 R

How to have recognized all the libraries Rpy2 R. Rpy2 not recognizing the libraries, utils, and tools. import rpy2.robjects as robjects R = robjects.r >>> R['library']("utils") RVector - Python:0x7f65fc85cfc8 / R:0x19bb980 >>> R['library']("tools") RVector - Python:0x7f65fc85f5a8 / R:0x2419140 (>>> from rpy2.robjects.packages import importr Traceback (most ...


python - Not recognized non existant file

im getting a weird error using this code (part of a class): from sys import path as workingDIR from os import system, path image = '' # some jpeg image data keep = 0 DIR = workingDIR[0] + '\\image' if path.isfile(DIR + '.jpeg'): # adding numbers to end of file name like how windows prevents multiple files having the same name x = 2 while path.isfile(DIR + ' (' + str(x) + ').jpeg'): ...


python - How to fix shebang flags that are not recognized on some systems

For some reason, the -O (optimized) flag is not recognized in the shebang line on a Red Hat Enterprise Server (release 5.3) that I access. On other systems, the flag is recognized without any issue. Executing the script below on OS X works fine. Recognition of the -O flag can be verified because it enables (when absent) or disables (when given) anything under the if __debug__


python - SCons, MSys, "not recognized as an internal or external command" error

I'm trying to use SCons to set up a project for compilation on Windows 7. In the MSys shell, I cd to the appropriate folder and run: scons target=setup ...and I get the following output: scons: Reading SConscript files ... SCons 2.0.1 OS="'{' is not recognized as an internal or external command, operable program or batch file." Compiler version check failed - need gcc 3.x o...


python - 'twistd' is not a recognized internal or external command

I'm trying to develop a Twisted Web server but can't seem to run the twistd command. I've tried setting the python path and even included the path to the twistd.py script in my Path but nothing seems to work. I'm using Twisted 12.0.0 and Python 2.7 on Windows. Any help would be hugely appreciated.


python - PPM file data cannot be recognized

I'm writing a simple picture editor. It uses PPM files. From what I can tell, I feel like my code should work. However, I get this error Traceback (most recent call last): File "/home/zach/Downloads/piceditor (1).py", line 84, in <module> main() File "/home/zach/Downloads/piceditor (1).py", line 69, in main image = Image(Point(100,100), filename) File "/home/zach/Downloads/graphics.py", ...


tkinter - Python-tk package not recognized in Python 2.7.3






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top