Return to main menu function for python calculator program

2024/10/6 9:02:43

I was asked to write a calculator in Python, and I completed it, but there is only one issue that needs to be fixed.

What is the prerequisite? "Once the user inputs/selects an arithmetic operation, the program should ask the user to enter the two operands one by one, separated by Enter key. If the user made a mistake while entering the parameters, he can return to main menu by pressing ‘$’ key at the end of the input string, followed by the Enter key.

I'll give you the code I wrote here, and I'd appreciate it if you could make this to get the return function.

def Add(a, b):return a + b# Function to subtract two numbers 
def Subtract(a, b):return a - b# Function to multiply two numbers
def Multiply(a, b):return a * b# Function to divide two numbers
def Divide(a, b):return a / b# Function to power two numbers
def Power(a, b):return a ** b# Function to remaind two numbers
def Remainder(a, b):return a % bdef Reset(a,b):return print(choice)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    : $ ")# take input from the userchoice = input("Enter choice(+,-,*,/,^,%,#,$): ")print(choice)if choice in ('+', '-', '*', '/', '^', '%', '#', '$'):if choice == '#':print("Done. Terminating")breaka = input('Enter first number: ')print(str(a))b = input('Enter second number: ')print(str(b))if choice == '+':print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))elif choice == '-':print(float(a), "-",float(b), "=", Subtract(float(a), float(b)))elif choice == '*':print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))elif choice == '/':if int(b) != 0:print(float(a), "/", float(b), "=", Divide(float(a), float(b)))breakelse:print("float division by zero")print(float(a), "/", float(b), "=", "None")elif choice == '^':print(float(a), "**",float(b), "=", Power(float(a), float(b)))elif choice == '%':print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))breakelse:print('Not a valid number,please enter again.')```
Answer

This kind of task is best (IMHO) handled in a so-called "table driven" manner. In other words, you create a table (in this case a dictionary) that has all the options built into it. Your core code then becomes much easier and the functionality is more extensible because all you need to do is add to or take away from the dictionary.

This structure also demonstrates how the user can be prompted for more input if/when something goes wrong.

def Add(a, b):return a + bdef Subtract(a, b):return a - bdef Multiply(a, b):return a * bdef Divide(a, b):return a / bdef Power(a, b):return a ** bdef Remainder(a, b):return a % boptions = {'+': ('Add', Add, '+'),'-': ('Subtract', Subtract, '-'),'*': ('Multiply', Multiply, '*'),'/': ('Divide', Divide, '/'),'^': ('Power', Power, '**'),'%': ('Remainder', Remainder, '%'),'#': ('Terminate', None)}while True:print('Select operation: ')for i, (k, v) in enumerate(options.items(), 1):print(f'{i}. {v[0]:<10}: {k} : ')option = input(f'Enter choice ({",".join(options.keys())}) : ')if control := options.get(option):_, func, *disp = controlif not func:breaka = input('Enter first number: ')b = input('Enter second number: ')try:a = float(a)b = float(b)print(f'{a} {disp} {b} = {func(a, b)}')except (ValueError, ZeroDivisionError) as e:print(e)else:print('Invalid option!')
https://en.xdnf.cn/q/120405.html

Related Q&A

what the code to use in # Complete this function with recursion in lines 4

# TODO: 2. Create a function that counts the sum of all the numbers in a list belownumber = [1,2,3,4,5] # Use this list as inputdef hitung_total(listKu):# Complete this function with recursionreturn li…

Pip cannot install some Python packages due to missing platform tag in M1 Mac

Lately I have been facing issues installing packages through pip. For e.g. when I try to install the torch package, it fails with the below error > arch arm64 > python --version 3.10.12 ❯ pip --…

find (i,j) location of closest (long,lat) values in a 2D array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

an error occured to add picture in python

I am new in python and I am using python 3.5 version. I want to add photo to python, and heres the code I wrote:from tkinter import * win=Tk() win.title("Python Image")canvas=Canvas(win,width…

Implementing stack in python by using lists as stacks [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Addition function in Python is not working as expected

I tried to create a function using which I want to do mathematical operations like (Addition and Multiplication), I could able to prompt the values and when I insert the values result is not returning …

Probability Distribution Function Python

I have a set of raw data and I have to identify the distribution of that data. What is the easiest way to plot a probability distribution function? I have tried fitting it in normal distribution. But …

how to convert a np array of lists to a np array

latest updated: >>> a = np.array(["0,1", "2,3", "4,5"]) >>> a array([0,1, 2,3, 4,5], dtype=|S3) >>> b = np.core.defchararray.split(a, sep=,) >…

Regex stemmer code explanation

Can someone please explain what does this code do?def stemmer(word):[(stem,end)] = re.findall(^(.*ss|.*?)(s)?$,word)return stem

Scraping data from a dynamic web database with Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…