Return 如果用户在 Python 树中输入错误的选项,将向用户显示错误

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

我是 Python 的新手,我尝试做一个简单的代码,如果用户输入了错误的产品代码,他将得到 "error message" 并提示他再次输入.但我就是无法让它工作。有人可以帮忙吗。谢谢

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", "" )
root.left = Node(1,"Chicken", "")
root.left.right = Node(2,"Potato","")
root.right = Node(5,"AisKrim","")
root.right.left = Node(4,"Bag","")
root.right.right = Node(6,"TV","")

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)

有几个问题。首先,你需要处理搜索中没有定义p的情况,避免出现异常。

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

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

其次,递归代码应该return值。因此,您需要将 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")

请注意,每次调用搜索函数 return 都是递归调用的值。

下面的工作代码。谢谢 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", "" )
root.left = Node(1,"Ayam", "")
root.left.right = Node(2,"Itik","")
root.right = Node(5,"AisKrim","")
root.right.left = Node(4,"Kentang","")
root.right.right = Node(6,"Itik","")

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)