Reduce Re-use and Recycle!
Required Materials
OnlineGDB (login required)
Word processing software
Part A
One of the biggest benefits of writing code inside functions is that we can reuse the code. We simply call it whenever we need it!

Let’s take a look at a calculator program that could be rewritten in a more reusable way with functions. Notice that two floats (decimal numbers, but they can also include integers) are inputted by the user, as an operation that the user would like to do. A series of if statements are used to determine what operation the user has chosen, and then the answer is printed inside a formatted print statement.

num1 = float(input("Enter your first number: "))
num2 = float(input("Enter your second number: "))
operation = input("What operation would you like to do? Type add, subtract, multiply, or divide.")
if operation == "add":
print(num1, "+", num2,"=", num1 + num2)
elif operation == "subtract":
print(num1, "-", num2,"=", num1 - num2)
elif operation == "multiply":
print(num1, "*", num2,"=", num1 * num2)
elif operation == "divide":
print(num1, "/", num2,"=", num1 / num2)
else:
print("Not a valid operation.")
Your job is to rewrite the program using functions. We have already looked at a function that adds two numbers. Using that as a starting point, we could call the add function from within our program in this way:

if operation == "add":
result = add(num1, num2)
print(num1, "+", num2,"=",result)
Now it’s your turn to do the following:

Type all of the original code into a new file in OnlineGDB.
Copy the add function from the unit and paste it at the top of your program.
Write three additional functions: subtract, multiply, and divide. Pay careful attention to the parameters and return statement. Remember to put the three functions at the top of your Python program before your main code.
Rewrite the main code so that your functions are called.
Part B
There are many different ways that a user could tell us that they would like to add two numbers in our calculator program. The user could type “add”, “Add”, “ADD”, or “+”, to name a few possibilities. Of course, as humans, we know exactly what is meant, even if the word is capitalized. But the Python Interpreter can’t tell that “add” is the same as “Add”.

We can use a list to make our program a bit more robust. We can also use the IN operator to check for certain values in that list. Take a look at this if statement’s opening line:

if operation in ["add", "Add", "ADD", "+"]:
Make those changes in your program and verify that it works.
Consider all of the possible words the user might enter to subtract, multiply, or divide.
Rewrite the first lines of each of your if statements to use lists.
Thoroughly test your new program, trying out each of the four operations.
When you have tested your program, click the save button. Then click Share and copy the program link. Paste the link in a word processing document and submit using this unit’s dropbox. If your program does not work properly, also include a paragraph explaining what you did to troubleshoot it.

Answers

Answer 1

To rewrite the given calculator program using functions, you can follow these steps:

1. Start by copying all of the original code into a new file in OnlineGDB.

2. Copy the add function from the unit and paste it at the top of your program. This function should take two parameters, num1 and num2, and return the sum of the two numbers.

3. Write three additional functions: subtract, multiply, and divide. Each function should take two parameters and return the result of the corresponding operation. Here's an example of how you can implement the subtract function:

```

def subtract(num1, num2):

return num1 - num2

```

4. Put the four functions (add, subtract, multiply, and divide) at the top of your Python program before your main code.

5. Rewrite the main code to call the appropriate function based on the user's chosen operation. Use if statements to check the value of the operation variable and call the corresponding function. Here's an example of how you can modify the main code:

```

if operation == "add":

result = add(num1, num2)

print(num1, "+", num2, "=", result)

elif operation == "subtract":

result = subtract(num1, num2)

print(num1, "-", num2, "=", result)

elif operation == "multiply":

result = multiply(num1, num2)

print(num1, "*", num2, "=", result)

elif operation == "divide":

result = divide(num1, num2)

print(num1, "/", num2, "=", result)

else:

print("Not a valid operation.")

```

Now, let's move on to Part B.

To make the program more robust and accept different variations of the operation input, you can use lists and the in operator to check for certain values. Here's an example for the addition operation:

```

if operation.lower() in ["add", "+"]:

```

This will allow the program to accept variations such as "add", "Add", "ADD", or "+". You can apply the same approach to the subtract, multiply, and divide operations.

Remember to thoroughly test your program by trying out each of the four operations. Make sure to test different variations of the operation input to ensure that the program handles them correctly.

Once you have tested your program and it is working properly, save it and click the Share button. Copy the program link and paste it into a word processing document for submission.

If your program doesn't work properly, make sure to double-check your code for any errors or typos. You can also add print statements to debug and see the values of variables at different points in the program. If you're still having trouble, you can explain the steps you took to troubleshoot the program in your submission paragraph


Related Questions

How do I bypass blocksi on my school Chromebook

Answers

Answer:

Open Chrome Settings.

Click on the “Privacy”

Under “Content restrictions,” click on the “Block sites” button.

Enter the website address in the “URL” box and click on the “Add site” button.

Explanation:

you could power wash/reset your computer then delete the blocking site

Other Questions
Suppose we are considering a doubly linked list and p is some node in the list which has predecessor node.Select the most correct java code snippet that inserts new node with value x before the node p. (prev is a link to predecessor node).A. Node f= p.prev.Node q= new Node(x):q.prev f, q.next=p:f.next =q;p.prev = q.B. Node f=p.prev.Node q = new Node(x):q.prev = f, q.next = p:f.next = qC. Node f= p.prev. Node q= new Node(x); q.next = p; f.next = qD. Node f= p.prev. Node q = new Node(x): q.prev f; f.next =q; p.prev = q Connective tissue may contain which of the following components? Select all that apply. Correct answer. a.Intercellular substanceb.Collagenc.Macrophages d. Fibriblast which is not a subdomain of application development? jennifer eats breakfast every day with the same plate, cup, and fork. she must start with her fork on a folded napkin next to her plate. she is exhibiting the phenomenon of: 100 points Resolve Ella wheeler Wilcox poem whats the meaning of it? And whats the message of the poem like can someone explain the poem to me polypeptides that are folded into a rouhly spherical shape and may contain several types of secondary structures are classified as 2 (a) who were some of the principal muckrakers during the progressive era, and what did each try to do? the price elasticity of demand of a good depends in part on its relative necessity in comparison to other goods. assume the following goods all have approximately the same price. which of the goods has the most elastic demand? access to medicine for individuals with chronic illnesses the patient is taking phenazopyridine when assessing the urine what will the nurse expect ?a. Red colorb. Orange colorc. Dark amber colord. Intense yellow color the idea that firms will get the most for their money when they pay wages higher than the equilibrium wage is called: responses optimal-wage theory. optimal-wage theory. efficiency-wage theory. efficiency-wage theory. the insider-outsider model. the insider-outsider model. equilibrium-wage theory in his offer, the offeror stipulates that by remaining silent A. the offeree has accepted the offer. B. the offeree ignores the offer. C. the parties have never before done business with one another. D. according to the general rule, a contract has been formed. Paraphrase this.You may write me down in history, with your bitter, twisted lies, you may trod me in the very dirt. But still, like dust, Ill rise. the partial pressure of nitrogen in the atmosphere is 0.781atm. calculate the partial pressure in mmhg and torr. round each of your answers to 3 significant digits. The concern expressed in this excerpt helps explain why the British passed thea) Peace of Parisb) Proclamation of 1763c) Quartering Actd) Port Act why is integration so important in financial planning? all my silver or white gold jewelry shoots yellow orange how do i ajust my white balance to photograph silver diamond jewelry? using s-des, encrypt/decrypt the following pt/ct? twelve students took a placement exam with the following results. 90 64 99 71 72 93 40 85 45 50 55 66 what is the percentile rank of 64? round to the nearest percentile Various types of crimes, including property crimes, car thefts, and even violent crimes, occur on college campuses. The University of Denver reported that there are, on average, 2.4 bicycle thefts per month.92 Suppose a random month is selected. a. What is the probability that there will be exactly three bicycle thefts? b. What is the probability that there will be fewer than six bicycle thefts? c. What is the probability that there will be at least five bicycle thefts? d. Suppose there are between 2 and 10 (inclusive) bicycle thefts. What is the probability of more than five bicycle thefts? 6666652222-12 what can you do if the number is 2 times 6 times 8 times 9 and / 78