python program to manipulate a list of items using class -
i newbie python oop concept. need write program manipulate list of items(add, delete , display) using class. without class got output in way :
def add(): b=input("how many inputs? : ") print b if b==1: in1=input("enter item : ") a.append(in1) else: in2=input("enter items : ") a.extend(in2) print def delete(): c=input("which item delete? ") global a=[x x in if x != c] print def display(): print ans=true global a=[1,2,3,5,2] while ans: print (""" 1.add items 2.delete items 3.display items 4.exit/quit """) ans=raw_input("what do? ") if ans=="1": add() elif ans=="2": delete() elif ans=="3": display() elif ans=="4": print("\n goodbye") exit() else: print("\n not valid choice try again")
can me write same code using class?
just put functions in class....
the advantage class approach can have multiple lists being manipulated @ once, , when use class, doesn't depend on arbitrary global list name have picked.
additionally, using input
method. seems you're using python 2.7 (judging print
statements), you should using raw_input
. input
tries eval
gets back, whereas want raw string user has entered, raw_input
returns.
class itemlist: def __init__(self, list): self.a = list def add(self): b=raw_input("how many inputs? : ") print b if b==1: in1=raw_input("enter item : ") self.a.append(in1) else: in2=raw_input("enter items : ") self.a.extend(in2) print self.a def delete(self): c=raw_input("which item delete? ") self.a=[x x in if x != c] print self.a def display(self): print self.a ans = true a=[1,2,3,5,2] mylist = itemlist(a) while ans: print (""" 1.add items 2.delete items 3.display items 4.exit/quit """) ans=raw_input("what do? ") if ans=="1": mylist.add() elif ans=="2": mylist.delete() elif ans=="3": mylist.display() elif ans=="4": print("\n goodbye") exit() else: print("\n not valid choice try again")
Comments
Post a Comment