Helena Adams Helena Adams - 6 months ago 11
Python Question

Return error to user if user enter wrong option in Python Tree

i am totally new in Python, i try to do a simple code whereby if the user entered a wrong Product code, he will get an "error message" and he will be prompted to enter again. But i just cannot get it to work. Can somebody help. Thanks

class Node(object):
def __init__(self,val,key,Number):
self.val = val
self.key = key
self.number = Number
self.left = None
self.right = None

def search(value,p):
if(p.val == value):
print("You bought item:",p.val,",description:", p.key,"cost:", p.number)
return 1
else:
if(p.val !=None):
if(p.val < value):
search (value,p.right)
if(p.val > value):
search (value,p.left)
else:
print("You've entered a wrong option")

root = Node(3,"Chips", "$12" )
root.left = Node(1,"Chicken", "$13")
root.left.right = Node(2,"Potato","$14")
root.right = Node(5,"AisKrim","$15")
root.right.left = Node(4,"Bag","$16")
root.right.right = Node(6,"TV","$17")

option = int(input("Please enter code:"))
answer = search(option,root)

while (answer != 1):
print("You've entered a wrong option")
option = int(input("Please enter code:"))
answer = search(option,root)

Answer

There are a couple issues. First, you need to handle the case where p is not defined in search to avoid an exception.

def search(value,p):
    if p is None:
        return None

Adding that code to the beginning of the search function will avoid the basic exception that happens when searching fails and you reach a Node that doesn't exist.

Second, the recursive code should return values. So you need to change the else clause to something like:

else:
    if(p.val !=None):
        if(p.val < value):
            return search (value,p.right)
        if(p.val > value):
            return search (value,p.left)
    else:
        print("You've entered a wrong option")

Note that each call to the search function returns the value from the recursive call.

Comments