I am sure this is very simple but I can’t find an answer anywhere. Let’s say I have this simple temperature conversion program called ConversionSelector.py that looks like
# Helper function to print all menu items:
def displayMenu():
print 'Temperature Conversions Menu:';
print '(1) Convert Fahrenheit to Celsius';
print '(2) Convert Celsius to Fahrenheit';
# Main function to display menu and invoke user-selected conversion:
def select():
displayMenu();
choice = input('Enter choice number: ');
if (choice == 1):
F2C();
elif (choice == 2):
C2F();
else:
print 'Invalid choice: ', choice;
print 'Bye-bye.';
# Convert Fahrenheit temperature to Celsius temperature:
def F2C():
Fahrenheit = input('Enter degrees in Fahrenheit: ');
Celsius = (5.0 / 9.0) * (Fahrenheit - 32);
print Fahrenheit, 'Fahrenheit =', Celsius, 'Celsius';
# Convert Celsius temperature to Fahrenheit temperature:
def C2F():
Celsius = input('Enter degrees in Celsius: ');
Fahrenheit = (9.0 / 5.0) * Celsius + 32;
print Celsius, 'Celsius =', Fahrenheit, 'Fahrenheit';
I use a Mac but I can’t get this to run. For example, if I type in the terminal
python ConversionSelector.py it doesn’t do anything. (I have IDLE and Python Launcher installed).
Now when I open up Windows and type select() then it does show the menu with the choice to select from the two conversion methods. Typing the same in the Mac Python Shell gives me this error:
Traceback (most recent call last):
File “”, line 1, in
select()
NameError: name ‘select’ is not defined
I know this is probably something very simple that I am not doing. Any help will be greatly appreciated.
Add this to the bottom of your file:
This will make
python ConversionSelector.pyrun your select function. What’s happening here is that __name__ is__main__when invoking your script directly, so you need to tell the interpreter to run your main function.Alternatively, you could import your module from the interpreter. Run
pythonin the same directory as yourConversionSelector.pyfile. Then run:You could also run python with the
-ioption. Runningpython -i ConversionSelector.pywould import your module and insert all of its names in the global namespace, so you could just runselect().