How can I make a simple calculator in python 3?

2024/11/18 3:49:44

I'm making this calculator using python 3, and this is what I have so far:

print("Welcome to Calculator!")class Calculator:def addition(self,x,y):added = x + yreturn addeddef subtraction(self,x,y):subtracted = x - yreturn subtracteddef multiplication(self,x,y):multiplied = x * yreturn multiplieddef division(self,x,y):divided = x / yreturn dividedcalculator = Calculator()print("1 \tAddition")
print("2 \tSubtraction")
print("3 \tMultiplication")
print("4 \tDivision")
operations = int(input("What operation would you like to use?:  "))x = int(input("How many numbers would you like to use?:  "))if operations == 1:a = 0sum = 0while a < x:number = int(input("Please enter number here:  "))a += 1sum = calculator.addition(number,sum)print("The answer is", sum)
if operations == 2:s = 0diff = 0while s < x:number = int(input("Please enter number here:  "))s += 1diff = calculator.subtraction(number,diff)print("The answer is", diff)
if operations == 3:m = 0prod = 1while m < x:number = int(input("Please enter number here:  "))m += 1prod = calculator.multiplication(number, prod)print("The answer is", prod)
if operations == 4:d = 0quo = 1while d < x:number = int(input("Please enter number here:  "))d += 1quo = calculator.division(number, quo)print("The answer is", quo)

Addition and multiplication works just fine, subtraction and division are the problems here. One example for subtraction is if I tried using two numbers, 9 and 3, I would get -6... That is definitely incorrect. As for division, if I tried dividing two numbers, 10 and 2, I would get 0.2, which is also wrong. For division I've tried switching number and quo, and with the same problem (10 / 2), I would get 0.05... Also, I don't want to use any of the built-in functions for python, so just help me fix these errors the easiest way possible.

Answer

Your algorithm is wrong for subtraction and division. Let's look at subtraction:

s = 0
diff = 0
while s < x:number = int(input("Please enter number here:  "))s += 1diff = calculator.subtraction(number,diff)

Step through this in your head. If you're operating on two numbers (9 and 3), you will get diff = 9 - 0 = 9 on the first iteration and diff = 3 - 9 = (-6) on the next. That won't work.

Subtraction is addition if all the terms (but the first) are negated. If you think about it like that it's fairly simple:

terms = []
for _ in range(x):  # this is a more idiomatic way to iterate `x` timesnumber = int(input("Please enter number here: "))terms.append(number)
head, tail = terms[0], terms[1:]
result = head
for term in tail:result -= tail
return result

You can certainly condense this further

terms = [int(input("Please enter number here: ")) for _ in range(x)]
terms[1:] = [x * (-1) for x in terms[1:]]
return sum(terms)

Similarly with division, step through in your head:

d = 0
quo = 1
while d < x:number = int(input("Please enter number here:  "))d += 1quo = calculator.division(number, quo)
print("The answer is", quo)

With 10 and 2, you get first quo = 10 / 1 = 10 then quo = 2 / 10 = 0.2. Like we can generalize subtraction to be tail-negated addition, we can generalize division to be tail-inverted multiplication.

24 / 2 / 3 / 4 == 24 * (1/2) * (1/3) * (1/4)

And we can write the algorithm similarly.

terms = [int(input("Please enter number here: ")) for _ in range(x)]
head, tail = terms[0], terms[1:]
result = head
for term in tail:result /= term

Note that all of these can also be written with functools.reduce and one of the operator functions

terms = [int(input("Number please! ")) for _ in range(int(input("How many numbers? ")))]
sum_ = functools.reduce(operator.add, terms)
diff = functools.reduce(operator.sub, terms)
prod = functools.reduce(operator.mul, terms)
diff = functools.reduce(operator.truediv, terms)
https://en.xdnf.cn/q/120121.html

Related Q&A

python 3: lists dont change their values

So I am trying to change a bunch of list items by a random percentage using a for loop.import random as rdm list = [1000, 100, 50, 25] def change():for item in list:item = item + item*rdm.uniform(-10, …

Using zip_longest on unequal lists but repeat the last entry instead of returning None

There is an existing thread about this Zipping unequal lists in python in to a list which does not drop any element from longer list being zipped But its not quite Im after. Instead of returning None, …

python scrapy not crawling all urls in scraped list

I am trying to scrape information from the pages listed on this page. https://pardo.ch/pardo/program/archive/2017/catalog-films.htmlthe xpath selector:film_page_urls_startpage = sel.xpath(//article[@cl…

Python - Do (something) when event is near [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…

Python script to find nth prime number

Im new to Python and I thought Id try to learn the ropes a bit by writing a function to find the nth prime number, however I cant get my code to work properly. No doubt this is due to me missing someth…

Printing values from list within an input range

I have an unordered list, lets say:lst = [12,23,35,54,43,29,65]and the program will prompt the user to input two numbers, where these two numbers will represent the range.input1 = 22input2 = 55therefor…

An issue with the tag add command of the ttk.Treeview widget - cant handle white space

I have noticed an issue with using the tag add command of a ttk.Treeview widget when activated with the tk.call() method. That is, it cant handle white space in the value of the str() elements of its i…

How to show the ten most overdue numbers in a list

I have asked a question before about this bit of code and it was answered adequately, but I have an additional question about showing the ten most overdue numbers. (This program was a part of an in-cla…

Connect a Flask webservice from a device which is not on the same network

I am not an expert in web programming and know very little about it. I am trying to run a webservice on an EC2 instance (Windows Server 2012R2) and the webservice is written in Python using Flask packa…

why int object is not iterable while str is into python [duplicate]

This question already has answers here:Why is int" not iterable in Python, but str are?(4 answers)Closed 2 years ago.As i know we can not iterate int value while we can iterate strings in python.…