python – Ask 2 terms from user and add them


Attributes, variable names, function names and function arguments should be lowercase / snake_case.

You should wrap your main procedure in a main function, as well as a if __name__ == '__main__' guard. More info.

Documentation makes your code easier to read and understand. Use docstrings and comments to explain why and how your code is doing what it’s doing.

Type hints make your code easier to read and understand, use them. PEP 484 | Python Docs


self.ex_variable = ex_variable
if self.coefficient < 0:
    self.ex_variable = "-" + self.variable

Depending on the value of self.coefficient, self.ex_variable will either be a number or a string. Sticking to the number representation seems more intuitive here:

self.ex_variable = ex_variable
if self.coefficient < 0:
    self.ex_variable = self.variable * -1

On closer inspection, your main functionality always passes strings to the constructor of TermEva. I don’t think this is intended, as your implementation of TermEva implies the arguments are numbers. You should generally check user input for correctness and then convert it to the desired type.


f-strings are a great tool for string formatting:

def sim_term(self):
    return f"{self.coefficient}{self.variable}"


This pattern of list creation

expanded_form = ()
for num in range(abs(self.Coefficient)):

can (and often should) be replaced by a more functional approach:

  • return (self.ex_variable for _ in range(abs(self.coefficient)))
  • return (self.ex_variable) * abs(self.coefficient)

Note that it’s convention to use _ as a variable name for loop variables you don’t actually use. This makes it immediately clear to the reader that the value of num is not needed.