0

I'm writing a python calculator, here is the code:

#Python Calculator

import sys;
import cmath;

def plus():
    num1 = float(input("Input the first number: "));
    num2 = float(input("Input the second number: "));
    ans = (num1 + num2);
    print(ans);
    exit();
    return;

def minus():
    num1 = float(input("Input the first number: "));
    num2 = float(input("Input the second number: "));
    ans = (num1 - num2);
    print(ans);
    exit();
    return;

def divide():
    num1 = float(input("Input the first number: "));
    num2 = float(input("Input the second number: "));
    ans = (num1 / num2);
    print(ans);
    exit();
    return;

def multiply():
    num1 = float(input("Input the first number: "));
    num2 = float(input("Input the second number: "));
    ans = (num1 * num2);
    print(ans);
    exit();
    return;

def power():
    num1 = float(input("Input the number: "));
    num2 = float(input("Input the power: "));
    ans = cmath.pow(num1, num2);
    print(ans);
    exit();
    return;

def square():
    num1 = float(input("Input the number: "));
    ans = cmath.sqrt(num1);
    print(ans);
    exit();
    return;

def inputs():
    print("Select which function you would like to use:");
    print("1 for Plus");
    print("2 for Minus");
    print("3 for Divide");
    print("4 for Multiply");
    print("5 for Power");
    print("6 for Square Root");
    func = input();

    if func == 1:
        plus();
    elif func == 2:
        minus();
    elif func == 3:
        divide();
    elif func == 4:
        multiply();
    elif func == 5:
        power();
    elif func == 6:
        square();
    return;

def exit():
    exit = str(input("Run again? y/n: "));
    if exit == "Y" or exit == "y":
        inputs();
        print ("");
    elif exit == "N" or exit == "n":
        sys.exit();
    else:
        exit();
    return;

print ("Python Calculator");
print("");
inputs();

Now the problem is, once you have inputted the function you want to run, the program just closes. I am relatively new to python, but not to programming. Also is anything wrong with the way this is coded (i.e. sloppy coding) please tell me.

4
  • 6
    You know that you don't need to put semicolons in the end of each string, don't you? Commented Apr 4, 2012 at 10:47
  • You also don't need to explicitly return at the end of every function. Returning from a function is what happens anyway when it reaches the end. Also, while calling back to inputs() from exit() will work for a while, it's messy and suggests further misunderstanding of how functions work. Commented Apr 4, 2012 at 10:56
  • Anyway, to find out what is actually going wrong with the program, you should run it from an already existing command window (that won't close when the program exits). Commented Apr 4, 2012 at 10:57
  • 1
    You're suffering of the same bad design of this other question. I'm not advertising, but mine answer there is exactly appliable here too (with obviusly python3 corrections). Commented Apr 4, 2012 at 11:06

2 Answers 2

4

Your input is probably String (e.g. "6") instead of the number 6.

In general, I think that your code is unnecessary long, and breaks the Don't Repeat Yourself principle. For starters, you can ask for the two numbers in a single place, and then call the relevant function to perform the relevant operation.

A more concise design would use Python operators:

funcs=[operator.add, operator.sub, operator.div, 
       operator.mul, operator.pow, your_square_function]

You can ask for the function type, then call the relevant function (see Lev's answer).

There interesting case is sqr, which takes a single argument, instead if two. This can be solved by specifying the number of arguments each function takes:

funcs=[(operator.add, 1), (operator.sub, 2), (operator.div, 2),
       (operator.mul, 2), (operator.pow, 2), (your_square_function, 1)]

The solution is now simple - ask for the function number, ask for the right number of arguments, and call funcs[input_number][0].

This idea can be elaborated, so that the function name is also stored:

funcs=[("Plus", operator.add, 1),   ("Minus", operator.sub, 2), 
       ("Divide", operator.div, 2), ("Multiply", operator.mul, 2), 
       ("Power", operator.pow, 2),  ("Square root", your_square_function, 1)]

Now you program should look like (pseudocode):

 for f in funcs:
      print id, function_name
 ask for id
 ask for relevant number of arguments
 run funcs[id] with relevant number of arguments
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, python was inputting the "func" variable as a string, so that has fixed the program, now I need to work on a better design as you suggested. Again, Thank You!
You've picked the right language - you'll be surprised how short and readable your code will be.
0

As Adam notes, the problem is that you don't convert func to int. Since you also ask for advice about the code organization, I can suggest the following to get rid of the stacked elif clauses:

functions = [plus, minus, divide, multiply, power, square]
try:
    func = int(input())
    functions[func-1]()
except:
    print("Please choose an existing function number.")
    exit()

5 Comments

This can be expanded to operators - see my answer.
I'd be cautious about advising a python new comer to use an except all.
@MattH Would you write except (ValueError, IndexError) there?
The "ideal" way would be to catch ValueError and reply "Please enter a number" then IndexError with "Please enter a number from 1 to %s".
Or explicitly check if your list contains such index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.