I wanted to do it like in java but Python doesn't have do while
, so I came up with a function:
class trys:
def menu():
print("welcome to your soccer team")
print("1 team trip")
print("2 training")
print("3 football game")
print("4 plan training")
print("5 interview")
print("6 heal lesson")
menu()
the method:
def method(self):
option = int(input("type your option :"))
while option <0 or option >6:
menu()
p = trys()
p.method()
I want the function to be called if the user types a different number than the ones on the screen so I don't have to paste the code again. but I get this:
NameError: name 'menu' is not defined
Before getting into the problem itself, you have an infinite loop:
That said,
menu
it is a "class attribute" as defined, to access it from the instance method, you must do it as it is using the reference to the class:Also never do this:
The body of a class is evaluated and executed at definition time , when the module is executed or imported, not when the class is instantiated. Therefore, when you import the module that contains the class or execute it, a nice menu will appear on stdout without even instantiating the class, and we usually don't want that...
Normally the menus and user inputs that are usually used to generate class objects are not placed inside the class, but as mere functions in the module, leaving the class only to represent the object itself.
If you leave the menu in the class, your thing is possibly that you define it as a static method since it handles neither class attributes (class method) nor instance attributes (instance method):
Static methods in Python are normal functions that have some logical relationship with the class, but are not really an essential part of it since they do not modify or access attributes of the instance or class and therefore do not modify the behavior of the object or class. They could be defined outside without problems but it suits us for legibility or any other reason that they are part of it. They can be accessed by a class reference or commonly by an instance reference (
self
in this case), but they do not automatically receive either a class or instance reference as an argument (class methods and instance methods respectively). ).Though it wouldn't hurt to keep in mind that users are "naughty by nature" and keep in mind that you can enter something that isn't an integer.
or directly get rid of the conversion problem and use strings directly to differentiate the menu options.
in this case it would also be worth:
but not if you have more than 9 options, since strings are sorted in lexicographical order, so
2 > 10
.Finally, by convention class names always use CamelCase:
Why don't you use
self.menu()
?In fact, Python does not force us to use classes, but if you want to use them, you should take into account that the method
menu()
belongs to the instanceself
of your classtrys
:There may be other ways to do it but this can also be a good option, I hope it helps you