如果用户在Python树中输入错误的选项,则会向用户返回错误

时间:2016-05-14 00:29:26

标签: python binary-tree

我是Python的新手,我尝试做一个简单的代码,如果用户输入了错误的产品代码,他将收到一条“错误消息”,系统将提示他再次输入。但我无法让它发挥作用。有人可以帮忙。感谢

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)

2 个答案:

答案 0 :(得分:0)

下面的工作代码。谢谢djkrause!

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 is None:
    return 1

elif(p.val == value):
    print("You bought item no:",p.val,", the description", p.key, "and the cost is:", p.number)
else:
    if(p.val !=None):
        if(p.val < value):
            return search (value,p.right)
        if(p.val > value):
            return search (value,p.left)

root = Node(3,"Chips", "$12" )
root.left = Node(1,"Ayam", "$13")
root.left.right = Node(2,"Itik","$14")
root.right = Node(5,"AisKrim","$15")
root.right.left = Node(4,"Kentang","$16")
root.right.right = Node(6,"Itik","$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)

答案 1 :(得分:-1)

有几个问题。首先,您需要处理在搜索中未定义p以避免异常的情况。

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

将该代码添加到搜索功能的开头将避免在搜索失败并且您到达不存在的节点时发生的基本异常。

其次,递归代码应该返回值。所以你需要将else子句改为:

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")

请注意,每次调用search函数都会返回递归调用的值。