Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace if\else with loop?
#1
I have this program.
This question involves lines 25-51.
To solve the equations it has a long if\elif\else. I want to know if I can eliminate that by putting the operators in a list ["+", "-", "*", "/"] and use a for-loop to match them to a list like [add, sub, div, mult]?

something like:
text_in = StringVar()
add, sub, div, mult = solve
symbol_list = ["+", "-", "*", "/"]
operator_list = [add, sub, div, mult]

for i in range(len(symbol_list)):
    # select i from operator_list
    text_in.set(i)
I am probably showing my ignorance but...
Reply
#2
It would be helpful to see your long elifs, but I can tell you that your symbol list is a list of strings, not mathematical operators.

If is common to see people make a function for each operation and then send numbers there. That might be a better option.
Reply
#3
Of course. The standard library includes the operator module that has functions for those basic mathematical operations, e.g.

>>> import operator
>>> f = operator.add
>>> f(1, 2)
3
>>> f = operator.mul
>>> f(2, 3)
6
>>> 
It's really useful to be able to treat functions as values in the same way that, say, integers are values - being able to pass them around, or assign them to variables as I'm doing here.

Also, it sounds like having two separate lists is not what you want. Why not just have a dict that maps the symbol to the function instead?
Reply
#4
@ndc85430, show you the operator module to use
In addition, look at https://python-forum.io/Thread-if-struct...dictionary
It show how to convert if/else into a dict. The tutorial defines its own functions, but as @ndc85430 said there is the convenient operator module
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace for loop to search index position illmattic 5 1,272 Sep-03-2022, 04:04 PM
Last Post: illmattic
  Beginner problem, replace function with for loop Motley_Cow 9 4,612 Sep-13-2019, 06:24 AM
Last Post: Motley_Cow
  Search & Replace - Newlines Added After Replace dj99 3 3,392 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

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