Math problem in Python - pyqt5 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Math problem in Python - pyqt5 (/thread-19215.html) |
Math problem in Python - pyqt5 - rwahdan - Jun-18-2019 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-val2this is if the operation is taking 2 values, how to deal with this if it is more than that. RE: Math problem in Python - pyqt5 - ichabod801 - Jun-18-2019 What have you tried? RE: Math problem in Python - pyqt5 - michalmonday - Jun-18-2019 Hi, you could use eval(string) Quote:>>> eval("1+2+3")https://docs.python.org/3/library/functions.html#eval RE: Math problem in Python - pyqt5 - ThomasL - Jun-18-2019 (Jun-18-2019, 03:44 PM)michalmonday Wrote: Hi, you could use If proposing eval() you should also provide this warning information.
RE: Math problem in Python - pyqt5 - ichabod801 - Jun-18-2019 And given that this is in the homework section, I seriously doubt the teacher is going to accept eval as a valid answer. RE: Math problem in Python - pyqt5 - noisefloor - Jun-18-2019 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 RE: Math problem in Python - pyqt5 - Gribouillis - Jun-18-2019 The if operator = '+':is not valid python code. Please post code that runs for real in the python interpreter. |