Hi I am new to the forums and to Python!

I am having trouble displaying a text menu in the following format
1: Name
2: Name
3: Name

It displays it correctly but then it gives an error message: Below is the code with output and error message.

#CreateMenu.py
#Create a standard text menu

#Create class menu

class TextMenu:
def __init__(self, listMenu):
self.listMenu = listMenu

#print menu
def __str__(self):
self.i = 1
self.index = len(self.listMenu)
while self.i < self.index:
print str(self.i) + ': ' + self.listMenu[self.i]
self.i = self.i + 1

#Test menu
list =
Menu = TextMenu(list)
print Menu

# Here is the output - with the error message
Evaluating CreateMenu.py
1: one
2: two
3: three
4: four
TypeError: __str__ returned non-string (type NoneType)

Any help would be appreciated.

PS: My code was indented - the indentation was removed when I posted

Recommended Answers

All 4 Replies

I have worked on the program some more, added a few things and updated the TextMenu class - however after all text that I print it prints "none". I have attached the code.
Here is the output:

Calculator ver.0.1
Help!
Enter a number corresponding to the action you want.

Created by Zagrijs Venter

None # It prints none after the help method is run
1: one
2: two
3: three
4: four
None # it prints none after the TextMenu method is run

The indentation problem is frustrating, but is solved by use of the [ code="Python"] and [/code] tags.

The problem with the original TextMenu was that __str__ methods are not supposed to print things, but instead return a printable string. Like this:

class Thingy(object):
   def __init__(self):
        self.items = [0,1,2,3]

   def __str__(self):
        s = ""
        for x in self.items:
            s += str(x)
        return s

so, what you want to do is build up the return string and then pass it back to the caller (which may be a print statement, or a str() function, or whatever).

Jeff

For posting Python code on Daniweb:
Please use the [code=python] and [/code] tag pair to enclose your python code.

Another note: Also make sure that the thread's title has something to do with your problem.

Thanks

I have managed to fix the code now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.