Python Forum
Math problem in Python - pyqt5
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Math problem in Python - pyqt5
#1
Hi,

I have a calculator project, I am able to give 2 numbers and operator to get answer after pressing = sign. Example, 1+2=3. Now, what if the user keeps adding operators before pressing the = sign. Example, 1+2+3+4+5+6+7=answer. how to track them all? I have a function that will take the first operation 1+2 passing 2 variables and an operator. How can I deal with such problem if the list is long before pressing the = sign?

def math(val1,operator,val2):
    if operator = "+":
        return val1+val2
    elif operator = "-":
        return val1-val2
this is if the operation is taking 2 values, how to deal with this if it is more than that.
Reply
#2
What have you tried?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Hi, you could use eval(string)
Quote:>>> eval("1+2+3")
6
https://docs.python.org/3/library/functions.html#eval
Reply
#4
(Jun-18-2019, 03:44 PM)michalmonday Wrote: Hi, you could use eval(string)
If proposing eval() you should also provide this warning information.
Reply
#5
And given that this is in the homework section, I seriously doubt the teacher is going to accept eval as a valid answer.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
Hi,

eval is evil, don't do that.

@rwahdan: in case your calculator has to accept a long(er) operation like 1+2+3+4, put the operation in a list, iterate over the list and make the calculations.

When you think about it, you can make it even more complicated, like 1+2*3 is mathematically correct 1+(2*3) = 7 - but if you would evaluate plain left to right, you would get 9... Do you want to / have to deal with invalid input like 1+-3?

Regards, noisefloor
Reply
#7
The
if operator = '+':
is not valid python code. Please post code that runs for real in the python interpreter.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  First Day using Python. NEED Simple Math CODE HELP! Jesseluke 4 1,320 Jan-13-2023, 01:04 PM
Last Post: jefsummers
  reverse math in python, who will find the correct answer? Kakha 11 4,304 Jan-11-2021, 11:59 AM
Last Post: Gribouillis
  PyQt5 QPushButton Problem Hellmut 2 2,251 Dec-26-2020, 08:41 PM
Last Post: Hellmut
  Math Problem cryxma 2 1,884 Dec-21-2020, 09:53 PM
Last Post: Gribouillis
  math problem using recursion? mnh001 14 4,406 Sep-03-2020, 07:34 PM
Last Post: mnh001

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020