我是Python全新的,我嘗試做一個簡單的代碼,如果用戶輸入了錯誤的產品代碼,他會得到一個「錯誤消息」,他會被提示再次輸入。但我無法讓它工作。有人可以幫忙嗎?謝謝如果用戶在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)
好了,我沒運行的代碼與這三個行改變了我之前發佈的,它工作正常打印「你輸入了一個錯誤的選擇」爲遺失物品,併爲找到的項目的數據。 – djkrause