Concept explainers
For the below code I need to add a history list with below conditions,
Objectives
-
Extend the functionali of the the calculator to save and display the past results of the arithmetic operations
Stage 2: Save and display calculation history of the calculator
In this second stage of the assignment you will extend the given calculator program to record the calculations, and recall them as a list using an additional command '?'.
Task 1: Study the given code in the answer box and extend it to save each executed operation in a Python List.
- Declare a list to store the previous operations
- Save the operator, operands and the results as a single string, for each operation after each calculation
Task 2: implement a history() function to handle the operation '?'
- Display the complete saved list of operations (in the order of execution) using a new command ‘?’
- If there are no previous calculations when the history '?' command is used, you can display the following message "No past calculations to show"
Code:
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice):
if (choice == '#'):
return -1
elif (choice == '$'):
return 0
elif (choice in ('+','-','*','/','^','%')):
while (True):
num1s = str(input("Enter first number: "))
print(num1s)
if num1s.endswith('$'):
return 0
if num1s.endswith('#'):
return -1
try:
num1 = float(num1s)
break
except:
print("Not a valid number,please enter again")
continue
while (True):
num2s = str(input("Enter second number: "))
print(num2s)
if num2s.endswith('$'):
return 0
if num2s.endswith('#'):
return -1
try:
num2 = float(num2s)
break
except:
print("Not a valid number,please enter again")
continue
result = 0.0
last_calculation = ""
if choice == '+':
result = add(num1, num2)
elif choice == '-':
result = subtract(num1, num2)
elif choice == '*':
result = multiply(num1, num2)
elif choice == '/':
result = divide(num1, num2)
elif choice == '^':
result = power(num1, num2)
elif choice == '%':
result = remainder(num1, num2)
else:
print("Something Went Wrong")
last_calculation = "{0} {1} {2} = {3}".format(num1, choice, num2, result)
print(last_calculation )
else:
print("Unrecognized operation")
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
print("9.History : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
Trending nowThis is a popular solution!
Step by stepSolved in 4 steps with 4 images
- Look at the code below and use the following comments to incdicate the scope of the static variables or functions. Place the comment below the relevant line. Module scope Class scope Function scope The code runs. Use onlinegdb.com to see it run. Module scope means global but only known in this source file. Class scope means global but only known by the class. Function scope means global but only known in the function. Hide Comments 1 #include 2 static const int MAX_SIZE=10; 5 // Return the max value 6 static double max(double d1) 7 { static double lastMax = 0; lastMax = (di > lastMax) ? di : lastMax; return lastMax; 8 10 11 } 12 13 // singleton class only one instance allowed 14 class singleton 15 { public: static Singleton& getsingleton() { return theone; } // Returns the Singleton 16 17 18 19 20 friend std::ostream& operator<< (std::ostream& o, const Singleton& s); private: Singleton() { }; // Prevents more instances 21 22 23 24 25 static Singleton theone; 26 }; 27 Singleton…arrow_forwardastfoodStats Assignment Description For this assignment, name your R file fastfoodStats.R For all questions you should load tidyverse, openintro, and lm.beta. You should not need to use any other libraries. suppressPackageStartupMessages(library(tidyverse)) suppressPackageStartupMessages(library(openintro)) suppressPackageStartupMessages(library(lm.beta)) The actual data set is called fastfood. Continue to use %>% for the pipe. CodeGrade does not support the new pipe. Round all float/dbl values to two decimal places. All statistics should be run with variables in the order I state E.g., "Run a regression predicting mileage from mpg, make, and type" would be: lm(mileage ~ mpg + make + type...) To access the fastfood data, run the following: fastfood <- openintro::fastfood Create a correlation matrix for the relations between calories, total_fat, sugar, and calcium for all items at Sonic, Subway, and Taco Bell, omitting missing values with na.omit(). Assign the…arrow_forwardAssuming we have the following list: scientists = ["Galileo G.", "Charles D.", "Isaac N.", "Grace H."] And we want to add three more names: "Richard F.", "Marie S.", "Jocelyn B." Which of the following commands will work: Select one or more: a. scientists.append(["Richard F."]) scientists.append(["Marie S."]) scientists.append(["Jocelyn B."]) b. C. d. scientists.append("Richard F.") scientists.append("Marie S.") scientists.append("Jocelyn B.") scientists += ["Richard F.", "Marie S.", "Jocelyn B."] scientists.extend(["Richard F.", "Marie S.", "Jocelyn B."]) e. scientists.append(["Richard F.", "Marie S.", "Jocelyn B."])arrow_forward
- Include an inner listener class to handle the events from the Save Record button. WhenSave Record button is clicked, new customer record is inserted into the table named“CUSTOMER” and display a message “New Customer Record Inserted” in a dialog box.Include another anonymous inner listener class to handle the events from the Reset button.When Reset is clicked then clear all the text fields and place the cursor in the first text fieldto allow the user to re-enter the correct values and Write a code that includes an exception handler that deals with duplicate records (e.g. sameCustomer ID.) and database error (e.g. Error establishing a database connection).arrow_forwardNo written by hand solutionarrow_forwardPlease help with my C++Specifications • For the view and delete commands, display an error message if the user enters an invalid contact number. • Define a structure to store the data for each contact. • When you start the program, it should read the contacts from the tab-delimited text file and store them in a vector of contact objects. •When reading data from the text file, you can read all text up to the next tab by adding a tab character ('\t') as the third argument of the getline() function. •When you add or delete a contact, the change should be saved to the text file immediately. That way, no changes are lost, even if the program crashes laterarrow_forward
- This project involves generating a boarding pass ticket and storing it in a file. The application should take the passenger details as input. The details of the boarding pass are to be stored in a file. The details should include valid data such as: name, email, phone number, gender, age, boarding pass number, date, origin, destination, estimated time of arrival (ETA), departure time. The application should generate a boarding pass ticket using the boarding pass details. The generated ticket should contain the following information: Boarding Pass Number, Date, Origin, Destination, Estimated time of arrival (ETA), Departure Time Name, Email, Phone Number, Gender, Age Total Ticket Price The user will be required to enter their Name, Email, Phone Number, Gender, Age, Date, Destination, and Departure Time into the console or GUI. From the input the computer must generate the ETA and Ticket Price. The computer must generate the boarding pass number ensuring the number is unique. All…arrow_forwardStep1-Study the scenario below and create a Java Program for Builders Warehouse, The program must consist of a class called Materials to handle the details of the materials. The program should read the materials details from the material.txt file then use a LinkedList to store the material details. Then finally the products stored in the LinkedList must be displayed like the sample code below step 2-There must be clear code and a screenshot of the code running.arrow_forwardEach member in a group, create a directory (with your studentID) then create a file (.txt) with your first name, in the file, add text to tell your full name and describe in one line your short goal in this term as a student. Then, display the file content. Finally, rename the file (first nameGoal). You MUST have screenshots for the task and all steps (the commands and outputs).arrow_forward
- Please help me with these question. I am having trouble understanding what to do. Please use HTML, CSS, and JavaScript Thank youarrow_forwardWrite a program to add a name to the list box when pressing add command and using the input box to enter a name. Also, when you press the "remove" command, the name is removed. Then find a name when pressing search command, using the input box to write name and message box to show the result. Finally, close the program by pressing the exit command. Femove Search Extarrow_forwardFor this week's assignment you will allow the user to add employee, view all employees, search employee by ssn, and edit employee information. Below this is what its supposed to look like when completed. I have also included what I started to do but I can't figure out how to add the search by SSN option or the edit employee option. If you can give me a step by step on how to do this in python I would greatly appreciate it.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education