[Tutor] What's going on with this code? Error message supplied.

Alan G alan.gauld at freenet.co.uk
Sun Jul 10 10:16:23 CEST 2005


Nathan,

> Subject: [Tutor] What's going on with this code? Error message 
> supplied.
>

> Here is the error message:
>
> Traceback (most recent call last):
>  File "D:\GC.py", line 67, in ?
>    if option == 1:
> NameError: name 'option' is not defined

The error message tells you what is wrong, option is not defined at 
the
point where you are using it. Pythopn starts executing code from the 
top
so when it comes to your line

if option == 1

it doesn't know about anything called option, you haven't created it 
yet.
In fact you only ever create it inside the main_menu() function. But 
names
created inside functions are only seen inside the function  - they are
called "local" because they are localised to the function. You need
to create a variable outside the function, then return the value from
the function to that variabl;e like this:

option = main_menu()   # assign the value thus creating option
if option == 1:    # now you can test it


But your program has another problem.

> print main_menu()

main_menu is a function which prints a menu. You do not need to
use print here. There are print commands inside the function.
In fact what this says is print the return value of main_menu()
and, as it stands, you don't have a return value so Python will
print 'None', which you don't want.

> def main_menu():
>    print "OPTIONS MENU"
>    print "1) Calculate"
> ...
>    print "5) Quit"
>    option = input("What option would you like:" )
     return option

And finally to get my code above to work you need to return
the option value as shown above.

You might want to rethink using input() too sibnce it has some
security issues,

option = int(raw_input())

is safer and for youur purposes does the same thing.

Take some time to work through a tutorial, that should explain these
issues. In the long run it will be faster than writing code and
posting every problem here, then waiting for an answer!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list