4

I've asked a similar question but to no avail.

I am a novice programming student and I've only been taught some basic techniques. Part of a task is to create a recipe program which I've mostly done, there is just one part preventing me from finishing.

I am supposed to allow a user to call a previously created text file (I've done this bit), then after this the contents of this file should be displayed for them to see (I've also done this bit), however the user should be able to recalculate the servings and therefore change the quantity of the ingredients. So if the user entered: "I want 2 servings" and the original quantity for 1 serving was 100g it should now output 200g.

It is really frustrating me and my teacher expects this work tomorrow. Below is what I am supposed to allow the user to do.

The user should be able to retrieve the recipe and have the ingredients recalculated for a different number of people.

• The program should ask the user to input the number of people.

• The program should output:

• the recipe name

• the new number of people

• the revised quantities with units for this number of people.

I will post my actual code below to show what I have done so far, which is to allow a user to view and make a new recipe. But the revised quantities bit is missing.

I apologise if the code is messy or unorganised, I am new to this.

Code so far:

#!/usr/bin/env python

import time

def start():

    while True:

        user_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")

        if user_input == "N":
            print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
            time.sleep(1.5)
            new_recipe()

        elif user_input == "V":
            print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
            time.sleep(1.5)
            exist_recipe()

        elif user_input == "E":
            print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
            time.sleep(1.5)
            modify_recipe()

        elif user_input == "quit":
            return

        else:
            print("\nThat is not a valid command, please try again with the commands allowed ")


def new_recipe():
    new_recipe = input("Please enter the name of the new recipe you wish to add! ")
    recipe_data = open(new_recipe, 'w')
    ingredients = input("Enter the number of ingredients ")
    servings = input("Enter the servings required for this recipe ")

    for n in range (1,int(ingredients)+1):

        ingredient = input("Enter the name of the ingredient ")
        recipe_data.write("\nIngrendient # " +str(n)+": \n")
        print("\n")
        recipe_data.write(ingredient)
        recipe_data.write("\n")
        quantities = input("Enter the quantity needed for this ingredient ")
        print("\n")
        recipe_data.write(quantities)
        recipe_data.write("\n")
        unit = input("Please enter the unit for this quantity (i.e. g, kg) ")
        recipe_data.write(unit)
        print("\n")

    for n in range (1,int(ingredients)+1):
        steps = input("\nEnter step " + str(n)+ ": ")
        print("\n")
        recipe_data.write("\nStep " +str(n) + " is to: \n")
        recipe_data.write("\n")
        recipe_data.write(steps)
    recipe_data.close()

def exist_recipe():
    choice_exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
    exist_recipe = open(choice_exist, "r+")
    print("\nThis recipe makes " + choice_exist)
    print(exist_recipe.read())
    time.sleep(1)

def modify_recipe():
    choice_exist = input("\nOkay, it looks like you want to modify a recipe. Please enter the name of this recipe ")
    exist_recipe = open(choice_exist, "r+")    
    servrequire = int(input("Please enter how many servings you would like "))


start()

EDIT:

Below is an example creation of a text file (recipe) and it's output (the file is called bread.txt) Note the outputs are a bit messy, I will fix that once I can get the core of the program to work.

Creating a recipe

What would you like to do? 
 1) - Enter N to enter a new recipe. 
 2 - Enter V to view an exisiting recipe, 
 3 - Enter E - to edit a recipe to your liking. 
 4 - Or enter quit to halt the program 
 N

Okay, it looks like you want to create a new recipe. Give me a moment...

Please enter the name of the new recipe you wish to add! bread.txt
Enter the number of ingredients 3
Enter the servings required for this recipe 1
Enter the name of the ingredient flour


Enter the quantity needed for this ingredient 300


Please enter the unit for this quantity (i.e. g, kg) g


Enter the name of the ingredient salt


Enter the quantity needed for this ingredient 50


Please enter the unit for this quantity (i.e. g, kg) g


Enter the name of the ingredient water


Enter the quantity needed for this ingredient 1


Please enter the unit for this quantity (i.e. g, kg) l



Enter step 1: pour all ingredients into a bowl



Enter step 2: mix together



Enter step 3: put in a bread tin and bake

Viewing a recipe

What would you like to do? 
 1) - Enter N to enter a new recipe. 
 2 - Enter V to view an exisiting recipe, 
 3 - Enter E - to edit a recipe to your liking. 
 4 - Or enter quit to halt the program 
 V

Okay, Let's proceed to let you view an existing recipe stored on the computer

Okay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. bread.txt

This recipe makes bread.txt

Ingrendient # 1: 
flour
300
g
Ingrendient # 2: 
salt
50
g
Ingrendient # 3: 
water
1
l
Step 1 is to: 

pour all ingredients into a bowl
Step 2 is to: 

mix together
Step 3 is to: 

put in a bread tin and bake

And here is the output if you enter V:

This recipe makes bread.txt

Ingrendient # 1: 
flour
300
g
Ingrendient # 2: 
salt
50
g
Ingrendient # 3: 
water
1
l
Step 1 is to: 

pour all ingredients into a bowl
Step 2 is to: 

mix together
Step 3 is to: 

put in a bread tin and bake

I look forward to your replies.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
  • 2
    Your question is a bit vague, in that it's not really clear what your problem is. You suggest you want to read a text file and when you have a numerical value, multiply that to increase the quantity of an ingredient. All I can suggest is that when you read data from the file, if you know it's a number use something like `int(somevariablename)` to convert the string to an Integer, and thus be able to use it as a number. – Raceyman Mar 05 '15 at 19:39
  • Why are you using text files to store the recipes? Why not a database of some sort? I know that databases are kinda scary to new users, but once you get the hang of them, they'll save you in the long run. Besides the fact that they're more relevant in real-life situations. – James Mertz Mar 05 '15 at 19:42
  • @Raceyman Sorry I will try to clarify. Say I wanted to call a recipe that already exists (for example pie) A user would type pie or pie.txt and the contents would be displayed for the user to see the ingredients and amounts etc. So I, the user, should be able to modify the amounts of the ingredients so say I enter I want two servings, and the original recipe has 500 grams of flour for 1, it should output the new quantity, which is 1000g or 1kg. – SpartanSK117 Mar 05 '15 at 19:43
  • 2
    @KronoS I have thought about this myself, but our teacher insisted that we use text files and only python to create this program. She just taught us the basics of file handling and how to open, read and write to files and told us to create this. – SpartanSK117 Mar 05 '15 at 19:44
  • @SpartanSK117, this is a rather broad topic covering many potential techniques. If you narrow down your question to a more specific problem you might be able to get more help. SO is really meant to help solve individual problems, rather that cover a broad topic like this. – Raceyman Mar 05 '15 at 19:48
  • 1
    I'd use JSON for something like this. None of that nasty parsing logic to worry about. – Kevin Mar 05 '15 at 19:59
  • You need to devise some text-based format that the recipes are stored using. This will allow you to read any one of them back in and retrieve it's attributes (such as name, number-of -servings, & ingredient + quantity-list). A very simple format specification would be one line per item in the order shown. – martineau Mar 05 '15 at 20:11
  • The number of steps should be decided by the user rather than be set arbitrarily equal to the number of ingredients, – gboffi Mar 05 '15 at 20:23

1 Answers1

2

It looks like your recipe files look like this:

Ingrendient # N: 
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(After N ingredients...)
Step N: 
{INSTRUCTIONS}

So basically you want to read four lines at a time, discard the first, then assign the rest to something useful.

with open(path_to_recipe) as infile:
    ingredients = []
    while True:
        try:
            sentinel = next(infile) # skip a line
            if sentinel.startswith("Step"):
                # we're past the ingredients, so
                break
            name = next(infile)
            amount = next(infile)
            metric = next(infile)
        except StopIteration:
            # you've reached the end of the file
            break
        ingredients.append({'name':name, 'amount':float(amount), 'metric':metric})
        # use a dictionary for easier access

When we exit the with block, ingredients will be a list of dictionaries that can be used as follows:

for ingredient in ingredients:
    scaled_volume = ingredient['amount'] * scale # double portions? etc...
    print(scaled_volume, ingredient['metric'], " ", ingredient['name'])
# # RESULT IS:
300g flour
50g salt
1l water

You should be able to leverage all that to finish your assignment!

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • 2
    note that using itertools's [`grouper` recipe](https://docs.python.org/3/library/itertools.html#itertools-recipes) is the preferred way of grabbing multiple lines from a file, but I think it's beyond what you're expected to know at this point and would probably be less intelligible than doing it by hand this way. – Adam Smith Mar 05 '15 at 20:46
  • Thank you so so much! You are a godsend, I have spent an abnormal amount of time on this and it's finally fixed. Thank you so much!!! – SpartanSK117 Mar 06 '15 at 00:14
  • 2
    @SpartanSK117 Glad I could help. Just be sure that you UNDERSTAND what's being done in the code and how to apply it to future situations! I'm not interested in doing your homework for you if it means you don't get to learn the subject! – Adam Smith Mar 06 '15 at 00:16
  • I definitely understand now! I am putting comments in the code right now and I've also learned some new skills to use. Thanks again!! – SpartanSK117 Mar 06 '15 at 00:28