In: Computer Science
Write a Python program that will perform various calculations (addition, subtraction, multiplication, division, and average).
The program will add, subtract, multiply, or divide 2 numbers and provide the average of multiple numbers inputted from the user.
You need to define a function named performCalculation which takes 1 parameter. The parameter will be the operation being performed (+,-,*,/). This function will perform the given prompt from the user for 2 numbers then perform the expected operation depending on the parameter that’s passed into the function. This function will print the calculated value.
You need to define a function named calculateAverage which takes no parameters. This function will ask the user how many numbers they wish to input. This function will use the number of times to run the program within a for loop in order to calculate the total and its average. This function will print the calculated average.
You need a main section that contains a while loop. The while loop will be used to allow the user to run the program until they enter a value which ends the loop. The main should prompt the user for the operation (+,-,*,/, or avg) they wish to perform. The main should evaluate the entered data using if statements. The main should call the necessary function to perform the calculation.
CODE:
def calculateAverage(): total = 0 x = int(input("how many numbers: ")) for i in range(x): n = int(input("Enter number {0}: ".format(i + 1))) total += n print("Total: ", total) print("Average: ", total / x) def performCalculation(operator): ans = 0 a = int(input("Enter 1st number: ")) b = int(input("Enter 2nd number: ")) if operator == "+": ans = a + b elif operator == "-": ans = a - b elif operator == "*": ans = a * b elif operator == "/": ans = a / b print("Answer: ", ans) if __name__ == '__main__': while True: print("1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Avg\\Total\n0.Exit\n") choice = int(input("Enter your choice: ")) if choice==1: performCalculation("+") elif choice==2: performCalculation("-") elif choice == 3: performCalculation("*") elif choice == 4: performCalculation("/") elif choice == 5: calculateAverage() elif choice == 0: break
OUTPUT:
Please upvote if you like my answer and comment below if you have any queries or need any further explanation.