Python Forum
Please help me refactor my clunky fridge script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please help me refactor my clunky fridge script
#4
You are already looping through fridge in the outer loop. You don't want to do that in the inner loop as well. The inner loop should be over the items in that food type:

for food_type, food_items in fridge.items():
    print("\n" + food_type.title() + ":")
    for item in food_items:
        print("\t" + item.title())
(Oct-12-2019, 07:02 AM)Brompy Wrote: I'd like to just format the output correctly

Then I really suggest looking at the output formatting options in Python. I tend to use the format method of strings:

for food_type, food_items in fridge.items():
    print("\n{}:".format(food_type.title()))
    for item in food_items:
        print("\t{}".format(item.title()))
That's a good method for backward compatibility. It replaces the curly braces ({}) with the parameters to the format method. The newer f-strings are easier, and allow you just put the expressions in the curly braces:

for food_type, food_items in fridge.items():
    print(f"\n{food_type.title()}:")
    for item in food_items:
        print(f"\t{item.title()}")
The first line is 86 characters long. I don't think that's very long at all. It's just over the 79 character limit in PEP8, which is very restrictive. I don't worry until lines are over 108 characters. But there is a balance there in terms of readability, and experience level plays into that. When things do go over the limit, I recommend refactoring the line into separate expressions rather than continuing it across multiple lines. So if that line is hard for you to read, you might write it as:

food_types = 'fruits meats dairy vegetebales sauces sweets'.split()
fridge = {food: [] for food in food_types}
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: Please help me refactor my clunky fridge script - by ichabod801 - Oct-12-2019, 01:23 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020