0% found this document useful (0 votes)
25 views5 pages

Recipe Multiplier Program in Python

Uploaded by

experimentprueba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views5 pages

Recipe Multiplier Program in Python

Uploaded by

experimentprueba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming Exercise 9:

Your Own Recipe Multiplier Program


[Last_First_recipe.txt]
Review. In lesson 4, you learned how to create variables for storing numbers using
input statements in combination with the float() function. The float() function was
necessary because Python sets the data type of values assigned using the input()
function as text by default.

Purpose. In this last exercise, you will learn how to “hardwire” a variable with a
numeric value. You’ll also learn another useful application of the hash symbol for
comments, to provide a detailed description of a variable in the variables code
block and to explain a calculation in the calculations code block. And finally, you
are going to learn in this lesson how to check for valid inputs using a while loop!

“Hardwiring” a variable with a numeric value.

Here are some examples of ingredient variables for a recipe


assigned a numeric value.

Remember that, in Python, when you get the value of a


variable from the program user with an input() function, the
value is read as text by default and you had to use the float() function to convert it
to a floating-point number. But a number value assigned by the programmer in the
code (“hardwired”) is read as a number and does not have to be converted from
text to a number.

Using the hash symbol for in-line comments.

So far you have only used comments in your source code at the beginning of the
source code to provide basic documentation, and as a label to identify each block
of your code. In this program you will use comments to clarify abbreviated variable
names and to explain the purpose of a calculation.

For example, the first two variable names shown above, tspSugar and ozMilk, you
might add inline comments explaining that tsp is an abbreviation for teaspoon, and
oz is an abbreviation for ounces, like this:
tspSugar = .5 # tsp is an abbreviation for teaspoon
ozMilk = 4 # oz is an abbreviation for ounces
Programming Exercise 9: Your Own Recipe Multiplier Program [[Link]]

So, what is the problem this program solves? Whenever you use a recipe, you know
that the quantities of ingredients given in the recipe are for a certain number of
servings, yes? The problem this program solves is adjusting the quantities of
ingredients in a recipe to make a number of servings that’s different from the number
of servings given for the recipe.

The formula for adjusting the quantities needed is very simple: qn = qg * sw / sg


where qn represents the quantity of any ingredient needed, qg represents the
quantity of that ingredient given in the recipe, sw is the number of servings wanted,
and sg is the number of servings given in the recipe.

Here is an example: my recipe for Tofu with Peanut Ginger Sauce provides quantities
of ingredients needed to make 4 servings. One of the ingredients is peanut butter.
The quantity given in the recipe is 4 tablespoons. But let’s say I want to make 8
servings; how much peanut butter do I need?

Plugging my example ingredient into the formula for adjusting quantities looks like
this:

# variables code block


tbspPeanutButter = 4 # tbsp is an abbreviation for tablespoon

The variables code block would also have to include a variable for the number of
servings given, that is the number of servings you get using the ingredient quantities
given in the recipe. So, we might code the number of servings given like this:

serves = 4 # the quantities given in the recipe serve this many

Then, in the calculations code block, we have to calculate the quantities of each
ingredient needed to make the number of servings wanted.

#calculations code block


tbspPeanutButter = tbspPeanutButter * servings / serves

Note that the variable name for the quantity needed and the variable name for the
quantity given are the same. No reason to come up with a different name. We want
to replace the value assigned to the ingredient variable in the variables code block
with the value needed to make a different number of servings.

This calculation has to be done for each ingredient in the recipe.

The only variable that has to assigned a value with an input statement in this program
is the number of servings wanted.

Prof. Strait Python Lesson [Link] Page 2 of 5


Programming Exercise 9: Your Own Recipe Multiplier Program [[Link]]

The variable name for the number of servings wanted could be servings. This variable
quantity is going to be input by the user, so the variable definition in your code would
include both the input() and float() functions you’ve already learned. A comment
would not be needed to explain the meaning of this variable because that job
should be done by the input prompt, like so:

servings = float(input(“How many servings do you want to make? “))

In the example ingredient names above, I’ve used very brief variable names that are
combinations of a unit of measure and an ingredient name.

For each ingredient in your recipe, I want you to create simple variable names from
combinations of the ingredient name and the unit of measure.

For example, let’s say you have a recipe calling for 2/3 cup rice. Combine the
ingredient name and the unit of measure like this: cupRice. Assign the quantity given
like this: cupRice = 2/3

You don’t have to add a comment to every variable definition; just the first time you
use a particular abbreviation.

Then in the calculations code block you would use a comment to explain a
calculation like this:

cupRice = cupRice * servings / serves # adjust for number of servings wanted

Check for valid inputs using a while loop.

In previous lessons you have not attempted to check for valid input when writing
input statements. In this lesson, there is only one variable being defined with an input
function and that is the number of servings desired.

It is quite easy to test for valid input in this case. Remember that any characters input
by the program user in Python are saved as text by default. When you have wanted to
have an input saved as a number, you have used the float() function around the input()
function to tell the computer to save the number entered by the user as a floating point
number rather than as text.

Only numbers can be saved as floating-point numbers. If the user were to enter
anything but a number at the prompt, the attempt to convert the input to a floating-
point number would cause an error.

Prof. Strait Python Lesson [Link] Page 3 of 5


Programming Exercise 9: Your Own Recipe Multiplier Program [[Link]]

If you have accidentally entered


letters at an input prompt that
must be saved as a floating-point
number, you have seen that the
program terminates, and an error
message is displayed like this:

Python provides an easy way to recognize that an error has occurred and gives
you an opportunity to inform the program user and require them to enter a
valid number.

This technique uses a while loop. You learned about the while loop in lesson 6. In
this case, we are using the while loop only for error handling, not to repeat the
entire program in a loop. The coding is therefore a little bit different from what
you did in lesson 6.

It would be coded like this for this program:

while True:
try:
servings = float(input(“How many servings do you want to make? “))
break
except ValueError:
print(“Your input is not a valid number. Please try again.”)

The while keyword is followed by the word True and a colon. The try and except
block is used to catch and handle exceptions (errors). The try clause runs as normal
code. If the code executes without error, the break command breaks out of the loop
and the program continues. The except clause runs only if an error occurs. If a
ValueError occurs, the print() function is executed and the program loops back to the
try clause.

Your Turn. Write a program to calculate ingredient quantities for a recipe of your
choice.

Your variable code block must include:


• A while loop to catch input errors
• An input variable asking the user how many servings of your recipe are
wanted
o The recipe you choose must have at least 3 ingredients
o The recipe you choose must be for more than one serving
o Be sure to include the name of your recipe in the prompt
• Hardwired quantities for at least 3 ingredients

Prof. Strait Python Lesson [Link] Page 4 of 5


Programming Exercise 9: Your Own Recipe Multiplier Program [[Link]]

• At least one example of a comment on the same line with code


Your calculations code block must include:
• a calculation to adjust the quantity of each ingredient
• code to format each adjusted quantity rounded to two decimal places using
the format() function, not the round() function!
Your output code block must include:
• the name of the recipe
• the number of servings input by the program user
• the full name and amount of each ingredient, like this:

In each of the previous exercises, I’ve broken the coding process down into small
discrete steps. For this last exercise, see if you can work through these steps to
develop this program organically on your own.

Refer to the examples above, and back to previous lessons, as needed. Remember
to test your code frequently as you work through the steps.

Prof. Strait Python Lesson [Link] Page 5 of 5

Common questions

Powered by AI

Expanding the program to include various ingredient units would involve defining multiple unit-specific variables and corresponding conversion factors. This would require additional code to handle conversions between units, requiring a comprehensive list of conversions and updates to the calculation and input handling sections to accommodate different units. This expansion would increase code complexity but enhance functionality allowing broader applicability for various recipes .

Hardwired variables have numeric values directly assigned in the code and do not require conversion since they are already recognized as numbers. User input variables, on the other hand, begin as text and require conversion via the float() function. Hardwired variables are used for ingredient quantities because they are constant values within the program, facilitating direct calculations without additional conversion steps .

Using the same variable name for both given and needed quantities simplifies the calculations block by eliminating the need for additional variable names, but it also risks confusion in tracking the change of data state through the program. This approach minimizes redundancy but requires careful comment documentation to ensure that the variable's role at each step is clear, thus balancing simplicity with potential readability issues .

The program solves the problem of adjusting ingredient quantities in a recipe to make a different number of servings than originally provided. It uses a formula qn = qg * sw / sg, where qn is the required quantity needed, qg is the quantity given, sw is the number of servings wanted, and sg is the number of servings given, to recalculate each ingredient's quantities .

The program uses a formula qn = qg * sw / sg to calculate the needed quantity of each ingredient. It ensures accuracy by taking the input number of servings wanted from the user, converting it into a floating-point number, and using hardwired ingredient quantities as a base for calculations. This process allows the program to modify ingredient amounts dynamically based on the specified number of servings .

The program's requirement to specify individual variable names for each ingredient limits scalability when handling complex recipes with numerous ingredients. Additionally, the repetition of calculations for each ingredient increases the coding workload and potential errors. While functional for simple recipes, these constraints necessitate additional features, like loops or data structures, to efficiently handle larger, more intricate recipes without excessive manual coding effort .

Input values are treated as text by default in Python, which is why converting them to numbers is necessary for performing mathematical operations. This conversion is achieved using the float() function around the input() function. For example, servings = float(input(“How many servings do you want to make? “)) converts the text input into a floating-point number .

Inline comments enhance code clarity by explaining variable abbreviations and the purpose of calculations, making it easier for others to understand the code. In the recipe multiplier program, they are used to clarify variable names, such as tspSugar meaning teaspoon of sugar, and to explain calculations, like adjusting ingredient quantities based on servings .

The while loop is used to repeatedly prompt the user for input until a valid number is entered. It uses a try-except block, where the try clause attempts to convert the input to a float. If this fails, a ValueError is caught, and a message prompts the user to enter a valid number. This process continues in a loop until valid input is provided, effectively preventing program termination due to input errors .

Using the format() function allows more precise control over how numbers are displayed, including specifying the number of decimal places, aligning data, and formatting strings consistently. This method ensures that output is uniform across different ingredients. However, it requires a greater understanding of formatting codes and may not be as straightforward for beginners compared to the round() function, which simply rounds to a specified number of decimal places .

You might also like