0

So I made a Calculator using python 2.7.8 and everything works like it should, unless one thing. I want to receive the error message "ERROR: Minimum Input: Number Operator Number!" when i for example try to calculate "2 +". But I can't get it working. Would be amazing if someone could point out what mistake(s) I made. Here is what is not working correctly:

except len(self.input) < 3:
        print "ERROR: Minimum Input: Number Operator Number!"

And here is the whole code:

import sys

class Calculator(object):

    def __init__(self, input):
        self.input = input

    def divide(self, number1, number2):
        return number1 / number2

    def add(self, number1, number2):
        return number1 + number2

    def sub(self, number1, number2):
        return number1 - number2

    def mult(self, number1, number2):
        return number1 * number2

    def modulo(self, number1, number2):
        return number1 % number2

    def exponentiate(self, number1, number2):
        return number1 ** number2

    def print_error(self, error):
        print error
        sys.exit(-1)

    def print_result(self, result):
        print result
        sys.exit(0)

    def process_input(self):
        try:
            result = float(self.input[1])
            current_operator = ""
            for element in self.input[2:]:
                if element in ["/", "+", "-", "*", "%", "**"]:
                    current_operator = element
                else:
                    number2 = float(element)
                    if current_operator == "/":
                        result = self.divide(result, number2)
                    elif current_operator == "+":
                        result = self.add(result, number2)
                    elif current_operator == "-":
                        result = self.sub(result, number2)
                    elif current_operator == "*":
                        result = self.mult(result, number2)
                    elif current_operator == "%":
                        result = self.modulo(result, number2)
                    elif current_operator == "**":
                        result = self.exponentiate(result, number2)
                    else:
                        self.print_error(error)

            self.print_result(result)
        except ZeroDivisionError:
            print "ERROR: Caught division by zero!"
        except ValueError:
            print "ERROR: Input number could not be parsed!"
        except OverflowError:
            print "ERROR: Result too large! Overflow encountered."
        except len(self.input) < 3:
            print "ERROR: Minimum Input: Number Operator Number!"

calc = Calculator(sys.argv)
calc.process_input()

Thanks for any answer!

GoBusto
  • 4,632
  • 6
  • 28
  • 45
Ergkuf
  • 1
  • 1
  • 2
    len(self.input) < 3 is not an exception – Yoriz Nov 09 '14 at 13:41
  • You may also want to try setting default values for you input, so in the case of your example `"2 +"` would evaluate to `"2 + 0`. To do this you do something like this `def add(self, number1=0, number2=0):`. This sets the default values of number1 and number2 to 0. I suggust this because `len(self.input) >= 3` assumes that you will get input in the form `x+y` with no spaces because spaces count when calculating the length. `len(`x+y`) = 3` while `len('x + y') = 5` so it would still be possible to get bad input even with this test because I could pass you something like this `'x + '` – guribe94 Nov 09 '14 at 15:19
  • Also, printing an error then immediately closing usually makes the error impossible to read. – Ben Morris Sep 23 '15 at 17:42

3 Answers3

1

As you have it, the code won't work. Instead, you'll need to either change this part into an if statement or manually raise an exception:

Old version - won't work.

try:
    # ...code...
except len(self.input) < 3:
    print "ERROR: Minimum Input: Number Operator Number!"

New version - Option A.

if len(self.input) < 3:
    print "ERROR: Minimum Input: Number Operator Number!"
else:
    # ...code...

New version - Option B.

try:
    if len(self.input) < 3:
        raise RuntimeError("Not enough arguments.")
    # ...code...
except RuntimeError:
    print "ERROR: Minimum Input: Number Operator Number!"

I've used RuntimeError as an example, you might want to use something more suitable instead.

GoBusto
  • 4,632
  • 6
  • 28
  • 45
0
try:
    assert len(self.input) >= 3
    # ...Your code...
except AssertionError:
    print "ERROR: Minimum Input: Number Operator Number!"

The problem is "except" must be followed by an exception and "len(self.input) >= 3" is not an exception ! (AssertionError is an exception)

Texom512
  • 4,785
  • 3
  • 16
  • 16
  • The `assert` statement will [not always work](https://docs.python.org/2/reference/simple_stmts.html#grammar-token-assert_stmt) for this: *The current code generator emits no code for an assert statement when optimization is requested at compile time.* Instead, it's better to explicitly `raise` an exception yourself. See also: http://stackoverflow.com/questions/9097706/why-assert-is-not-largely-used – GoBusto Nov 10 '14 at 14:12
0

user_info = input("Enter the following info- Name Age Favorite Sport: ") user_info_split = user_info.split() print "Hello, " + user_info_split[0] + "! " + "I also enjoy " + user_info_split[2] + "!"

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 10 '23 at 12:54