我的功能提前终止-如何修复

  • 本文关键字:何修复 终止 功能 python
  • 更新时间 :
  • 英文 :


我需要做哪些更改来纠正逻辑并允许它在整个函数中运行?

我试图调用一个函数,但每当函数到达用户输入"all"或"category"的行时,它就会停止工作。我试图做的是允许用户输入全部或类别,并让程序显示字典中列出的所有食谱,或者让程序只显示符合指定标准(类别(的食谱。有人能帮忙指出我的代码逻辑哪里不正确吗?

请注意,我正在尝试调用视图选择函数,每次我输入全部或类别时,它都会停止运行,我只是添加了其他函数,这样你就可以看到调用了什么。

def display_recipes(self):
"""Iterates through a dictionary and neatly displays its contents"""
for number in self.recipes:
print(f"n{number}")
for key, value in self.recipes[number].items():
print(f"t{key} : {value}")
def display_recipe_names(self):
"""Display each recipe and its cooresponding number"""
for number in self.recipes:
for key, value in self.recipes[number].items():
print (f"{number} : {self.recipes[number]['Recipie Name']}")
def view_choice(self):
"""Determine if the user wants to view all recipes or only recipes of a
selected category."""
decision = input("Would you like to view all recipes or would you like to "
"view recipes of a selected category? (all or category):  ")
if decision.lower == 'all':
self.display_recipes()
elif decision.lower == 'category':
print("Please select a category from the list below: ")
self.print_categories()
category_selection = input("Please select a category: ")
for number in self.recipes:
for key, value in self.recipes[number].items():
if category_selection.title() == self.recipes[number]['Category']:
print(f"{number}: {self.recipes[number]['Recipie Name']}")
break
def print_categories(self):
"""printing the list of unique catagories within the recipe book"""
for category in self.categories:
print(f"{category}")
print("")

您遇到的问题是,当您输入all时,decision.lower == 'all'分支没有触发。

您可以使用打印调试来帮助解开这个谜团。暂时添加一些类似的内容:

print("User entered string that should be equal to 'all':")
print(decision.lower)

该输出:

User entered string that should be equal to 'all':
<built-in method lower of str object at 0x7f02afa259f0>

Welp,你把一个方法比作一个字符串。这就是为什么它不匹配。然后,您可以更改它以运行方法print(decision.lower()),并验证它是否正确。

现在您可以将分支修改为if decision.lower() == 'all':,然后重试

相关内容

最新更新