Basic calculator in Python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
5
down vote

favorite
1












I am a beginner in Python, I want to know if this code can be improved. Is it possible to make it work without the if/else?



number1=int(input('Enter first number: '))
number2=int(input('Enter Second number: '))
operation=input("Enter operationn[+,-,*,/]")
if operation == '+':
sum=number1+number2
elif operation == '-':
sum =number1-number2
elif operation == '*':
sum =number1*number2
else:
sum =number1//number2
print(sum)






share|improve this question













migrated from stackoverflow.com Jun 21 at 9:28


This question came from our site for professional and enthusiast programmers.










  • 5




    An immediate improvement would be not to use sum as a variable name since it shadows a builtin.
    – roganjosh
    Jun 21 at 9:28










  • All operations except the last (//), I don't have a non-if/else solution for that. At least without resorting to eval, which should be avoided.
    – Mast
    Jun 21 at 9:40






  • 3




    sum =number1//number2, sure this totally represent a sum.
    – Mathias Ettinger
    Jun 21 at 10:11
















up vote
5
down vote

favorite
1












I am a beginner in Python, I want to know if this code can be improved. Is it possible to make it work without the if/else?



number1=int(input('Enter first number: '))
number2=int(input('Enter Second number: '))
operation=input("Enter operationn[+,-,*,/]")
if operation == '+':
sum=number1+number2
elif operation == '-':
sum =number1-number2
elif operation == '*':
sum =number1*number2
else:
sum =number1//number2
print(sum)






share|improve this question













migrated from stackoverflow.com Jun 21 at 9:28


This question came from our site for professional and enthusiast programmers.










  • 5




    An immediate improvement would be not to use sum as a variable name since it shadows a builtin.
    – roganjosh
    Jun 21 at 9:28










  • All operations except the last (//), I don't have a non-if/else solution for that. At least without resorting to eval, which should be avoided.
    – Mast
    Jun 21 at 9:40






  • 3




    sum =number1//number2, sure this totally represent a sum.
    – Mathias Ettinger
    Jun 21 at 10:11












up vote
5
down vote

favorite
1









up vote
5
down vote

favorite
1






1





I am a beginner in Python, I want to know if this code can be improved. Is it possible to make it work without the if/else?



number1=int(input('Enter first number: '))
number2=int(input('Enter Second number: '))
operation=input("Enter operationn[+,-,*,/]")
if operation == '+':
sum=number1+number2
elif operation == '-':
sum =number1-number2
elif operation == '*':
sum =number1*number2
else:
sum =number1//number2
print(sum)






share|improve this question













I am a beginner in Python, I want to know if this code can be improved. Is it possible to make it work without the if/else?



number1=int(input('Enter first number: '))
number2=int(input('Enter Second number: '))
operation=input("Enter operationn[+,-,*,/]")
if operation == '+':
sum=number1+number2
elif operation == '-':
sum =number1-number2
elif operation == '*':
sum =number1*number2
else:
sum =number1//number2
print(sum)








share|improve this question












share|improve this question




share|improve this question








edited Jun 21 at 9:43









Mast

7,32663484




7,32663484









asked Jun 21 at 9:26









ანრი ნაზარიანი

283




283




migrated from stackoverflow.com Jun 21 at 9:28


This question came from our site for professional and enthusiast programmers.






migrated from stackoverflow.com Jun 21 at 9:28


This question came from our site for professional and enthusiast programmers.









  • 5




    An immediate improvement would be not to use sum as a variable name since it shadows a builtin.
    – roganjosh
    Jun 21 at 9:28










  • All operations except the last (//), I don't have a non-if/else solution for that. At least without resorting to eval, which should be avoided.
    – Mast
    Jun 21 at 9:40






  • 3




    sum =number1//number2, sure this totally represent a sum.
    – Mathias Ettinger
    Jun 21 at 10:11












  • 5




    An immediate improvement would be not to use sum as a variable name since it shadows a builtin.
    – roganjosh
    Jun 21 at 9:28










  • All operations except the last (//), I don't have a non-if/else solution for that. At least without resorting to eval, which should be avoided.
    – Mast
    Jun 21 at 9:40






  • 3




    sum =number1//number2, sure this totally represent a sum.
    – Mathias Ettinger
    Jun 21 at 10:11







5




5




An immediate improvement would be not to use sum as a variable name since it shadows a builtin.
– roganjosh
Jun 21 at 9:28




An immediate improvement would be not to use sum as a variable name since it shadows a builtin.
– roganjosh
Jun 21 at 9:28












All operations except the last (//), I don't have a non-if/else solution for that. At least without resorting to eval, which should be avoided.
– Mast
Jun 21 at 9:40




All operations except the last (//), I don't have a non-if/else solution for that. At least without resorting to eval, which should be avoided.
– Mast
Jun 21 at 9:40




3




3




sum =number1//number2, sure this totally represent a sum.
– Mathias Ettinger
Jun 21 at 10:11




sum =number1//number2, sure this totally represent a sum.
– Mathias Ettinger
Jun 21 at 10:11










3 Answers
3






active

oldest

votes

















up vote
12
down vote



accepted










If you don't want any if statements then you can do the same with the operator library and a dictionary. This is by using the dict.get method that allows you to have a default value (operator.floordiv) if the value isn't in the dictionary. After getting a valid function from the dictionary, you then just have to call the function.



import operator

operators =
'+': operator.add,
'-': operator.sub,
'*': operator.mul


number1 = int(input('Enter first number: '))
number2 = int(input('Enter Second number: '))
operation = input("Enter operationn[+,-,*,/]")
print(operators.get(operation, operator.floordiv)(number1, number2))


I would however not assume division if the user enters random data. And so I'd add an if and else. In this case I'd check that the operator is in the operators dictionary, and perform the operation if it is. If it isn't, then I'd tell the user that they entered an invalid operator:



operators = 
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.floordiv


if operation in operators:
print(operators[operation](number1, number2))
else:
print('Invalid operator')


You can also make the operator list in the input automatically created from the dictionary too. To create the string '+,-,*,/' you can use ','.join(['+', '-', '*', '/']), to get the array you can then use operators.keys(). Finally you'd have to insert it into the rest of the string, and so I'd use str.format.



operation = input("Enter operationn[]".format(','.join(operators.keys())))


And so tying this all together you could use:



import operator

operators =
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.floordiv


number1 = int(input('Enter first number: '))
number2 = int(input('Enter Second number: '))
operation = input("Enter operationn[]".format(','.join(operators.keys())))
if operation in operators:
print(operators[operation](number1, number2))
else:
print('Invalid operator')





share|improve this answer





















  • Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
    – QuantumHoneybees
    Jun 22 at 13:21










  • @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
    – Peilonrayz
    Jun 22 at 13:42










  • The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
    – QuantumHoneybees
    Jun 22 at 20:33

















up vote
7
down vote













sum



you use sum as a variable name, shadowing the builtin, which is generally a bad idea



function



Divide the program into functions with their own goal. Here you have following part



  1. get the 2 numbers

  2. get the operation

  3. do the calculation

  4. present the result

Get the numbers



you ask for an input, which you get returned as a str. You convert this to a number with int. If the input is not an integer value, this will crash the program, so you'll need some sort of input validation.



For the input validation, I will borrow a bit from this answer to another question



def ask_number(message='please enter a number', number_types=None):
if number_types is None:
number_types = (int, float, complex)
while True:
number = input(message)
for converter in number_types:
try:
return converter(number)
except ValueError:
pass
else:
print('Please enter a valid number')


In this way, you can specify which types are valid, and in which order they should be tried. You can even use custom types if you want.



This will keep asking until you have a valid number, and can be stopped with ctrl+c, which will raise a KeyboardInteruptError



Get the operation



To make it easy for ourselves, we define the default options for operators



DEFAULT_OPERATIONS = 
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'//': operator.floordiv,
'/': operator.truediv,
'**': operator.pow,
'^': operator.pow,



This way we can call the function without arguments most of the times



def ask_operator(operators=None):
if operators is None:
operators = DEFAULT_OPERATIONS

message = f'Please select an operator from [','.join(map(str, operators)))]'
while True:
operator = input(message)
if operator in operators:
return operator
else:
print('Please enter a valid operator')


putting it together



def main():
operators = DEFAULT_OPERATIONS

number1 = ask_number('Please enter the first number:')
number2 = ask_number('Please enter the second number:')
operator_str = ask_operator(operators)
operator = operators[operator_str]

result = operator(number1, number2)

print(f'number1 operator_str number2 = result')


which you can put behing a if __name__ == '__main__'-guard



if __name__ == '__main__':
main()





share|improve this answer






























    up vote
    -3
    down vote













    You could use the exec function if you wanted, which takes a string formatted as python code and runs the code that the string represents. After the first three lines, just type:



    exec('sum = number1' + operation + 'number2')
    print(sum)


    You would also want to use an if statement to make sure "operation" is actually an operation before running the above lines, though. You don't want your user to type in something crazy and crash the program.






    share|improve this answer

















    • 2




      "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
      – Mast
      Jun 21 at 19:29






    • 3




      Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
      – Hosch250
      Jun 21 at 19:43










    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196961%2fbasic-calculator-in-python%23new-answer', 'question_page');

    );

    Post as a guest






























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    12
    down vote



    accepted










    If you don't want any if statements then you can do the same with the operator library and a dictionary. This is by using the dict.get method that allows you to have a default value (operator.floordiv) if the value isn't in the dictionary. After getting a valid function from the dictionary, you then just have to call the function.



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[+,-,*,/]")
    print(operators.get(operation, operator.floordiv)(number1, number2))


    I would however not assume division if the user enters random data. And so I'd add an if and else. In this case I'd check that the operator is in the operators dictionary, and perform the operation if it is. If it isn't, then I'd tell the user that they entered an invalid operator:



    operators = 
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')


    You can also make the operator list in the input automatically created from the dictionary too. To create the string '+,-,*,/' you can use ','.join(['+', '-', '*', '/']), to get the array you can then use operators.keys(). Finally you'd have to insert it into the rest of the string, and so I'd use str.format.



    operation = input("Enter operationn[]".format(','.join(operators.keys())))


    And so tying this all together you could use:



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[]".format(','.join(operators.keys())))
    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')





    share|improve this answer





















    • Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
      – QuantumHoneybees
      Jun 22 at 13:21










    • @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
      – Peilonrayz
      Jun 22 at 13:42










    • The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
      – QuantumHoneybees
      Jun 22 at 20:33














    up vote
    12
    down vote



    accepted










    If you don't want any if statements then you can do the same with the operator library and a dictionary. This is by using the dict.get method that allows you to have a default value (operator.floordiv) if the value isn't in the dictionary. After getting a valid function from the dictionary, you then just have to call the function.



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[+,-,*,/]")
    print(operators.get(operation, operator.floordiv)(number1, number2))


    I would however not assume division if the user enters random data. And so I'd add an if and else. In this case I'd check that the operator is in the operators dictionary, and perform the operation if it is. If it isn't, then I'd tell the user that they entered an invalid operator:



    operators = 
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')


    You can also make the operator list in the input automatically created from the dictionary too. To create the string '+,-,*,/' you can use ','.join(['+', '-', '*', '/']), to get the array you can then use operators.keys(). Finally you'd have to insert it into the rest of the string, and so I'd use str.format.



    operation = input("Enter operationn[]".format(','.join(operators.keys())))


    And so tying this all together you could use:



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[]".format(','.join(operators.keys())))
    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')





    share|improve this answer





















    • Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
      – QuantumHoneybees
      Jun 22 at 13:21










    • @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
      – Peilonrayz
      Jun 22 at 13:42










    • The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
      – QuantumHoneybees
      Jun 22 at 20:33












    up vote
    12
    down vote



    accepted







    up vote
    12
    down vote



    accepted






    If you don't want any if statements then you can do the same with the operator library and a dictionary. This is by using the dict.get method that allows you to have a default value (operator.floordiv) if the value isn't in the dictionary. After getting a valid function from the dictionary, you then just have to call the function.



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[+,-,*,/]")
    print(operators.get(operation, operator.floordiv)(number1, number2))


    I would however not assume division if the user enters random data. And so I'd add an if and else. In this case I'd check that the operator is in the operators dictionary, and perform the operation if it is. If it isn't, then I'd tell the user that they entered an invalid operator:



    operators = 
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')


    You can also make the operator list in the input automatically created from the dictionary too. To create the string '+,-,*,/' you can use ','.join(['+', '-', '*', '/']), to get the array you can then use operators.keys(). Finally you'd have to insert it into the rest of the string, and so I'd use str.format.



    operation = input("Enter operationn[]".format(','.join(operators.keys())))


    And so tying this all together you could use:



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[]".format(','.join(operators.keys())))
    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')





    share|improve this answer













    If you don't want any if statements then you can do the same with the operator library and a dictionary. This is by using the dict.get method that allows you to have a default value (operator.floordiv) if the value isn't in the dictionary. After getting a valid function from the dictionary, you then just have to call the function.



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[+,-,*,/]")
    print(operators.get(operation, operator.floordiv)(number1, number2))


    I would however not assume division if the user enters random data. And so I'd add an if and else. In this case I'd check that the operator is in the operators dictionary, and perform the operation if it is. If it isn't, then I'd tell the user that they entered an invalid operator:



    operators = 
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')


    You can also make the operator list in the input automatically created from the dictionary too. To create the string '+,-,*,/' you can use ','.join(['+', '-', '*', '/']), to get the array you can then use operators.keys(). Finally you'd have to insert it into the rest of the string, and so I'd use str.format.



    operation = input("Enter operationn[]".format(','.join(operators.keys())))


    And so tying this all together you could use:



    import operator

    operators =
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv


    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter Second number: '))
    operation = input("Enter operationn[]".format(','.join(operators.keys())))
    if operation in operators:
    print(operators[operation](number1, number2))
    else:
    print('Invalid operator')






    share|improve this answer













    share|improve this answer



    share|improve this answer











    answered Jun 21 at 10:04









    Peilonrayz

    24.3k336102




    24.3k336102











    • Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
      – QuantumHoneybees
      Jun 22 at 13:21










    • @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
      – Peilonrayz
      Jun 22 at 13:42










    • The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
      – QuantumHoneybees
      Jun 22 at 20:33
















    • Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
      – QuantumHoneybees
      Jun 22 at 13:21










    • @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
      – Peilonrayz
      Jun 22 at 13:42










    • The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
      – QuantumHoneybees
      Jun 22 at 20:33















    Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
    – QuantumHoneybees
    Jun 22 at 13:21




    Adding to the conciseness, and in the spirit of teaching Python, there's also a chance here to use the ternary operator and Python's dynamic typing to change the last four lines to a single line: print(operators[operation](number1, number2) if operator in operations else "Invalid Operator") This is basically equivalent to writing print(operation in operators ? operators[operation](number1, number2) : 'Invalid Operator') in a different language, but only works in a dynamically typed language like Python
    – QuantumHoneybees
    Jun 22 at 13:21












    @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
    – Peilonrayz
    Jun 22 at 13:42




    @QuantumHoneybees Honestly, I find it hard to read. And so I personally wouldn't recommend it here.
    – Peilonrayz
    Jun 22 at 13:42












    The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
    – QuantumHoneybees
    Jun 22 at 20:33




    The main goal was to introduce the ternary operator in Python, and so I do agree. Also, following the "zen of python" readability counts and your code is more readable, but I sometimes prefer a one-liner print statement for conciseness because too many if statements can make the code be unreadable
    – QuantumHoneybees
    Jun 22 at 20:33












    up vote
    7
    down vote













    sum



    you use sum as a variable name, shadowing the builtin, which is generally a bad idea



    function



    Divide the program into functions with their own goal. Here you have following part



    1. get the 2 numbers

    2. get the operation

    3. do the calculation

    4. present the result

    Get the numbers



    you ask for an input, which you get returned as a str. You convert this to a number with int. If the input is not an integer value, this will crash the program, so you'll need some sort of input validation.



    For the input validation, I will borrow a bit from this answer to another question



    def ask_number(message='please enter a number', number_types=None):
    if number_types is None:
    number_types = (int, float, complex)
    while True:
    number = input(message)
    for converter in number_types:
    try:
    return converter(number)
    except ValueError:
    pass
    else:
    print('Please enter a valid number')


    In this way, you can specify which types are valid, and in which order they should be tried. You can even use custom types if you want.



    This will keep asking until you have a valid number, and can be stopped with ctrl+c, which will raise a KeyboardInteruptError



    Get the operation



    To make it easy for ourselves, we define the default options for operators



    DEFAULT_OPERATIONS = 
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '//': operator.floordiv,
    '/': operator.truediv,
    '**': operator.pow,
    '^': operator.pow,



    This way we can call the function without arguments most of the times



    def ask_operator(operators=None):
    if operators is None:
    operators = DEFAULT_OPERATIONS

    message = f'Please select an operator from [','.join(map(str, operators)))]'
    while True:
    operator = input(message)
    if operator in operators:
    return operator
    else:
    print('Please enter a valid operator')


    putting it together



    def main():
    operators = DEFAULT_OPERATIONS

    number1 = ask_number('Please enter the first number:')
    number2 = ask_number('Please enter the second number:')
    operator_str = ask_operator(operators)
    operator = operators[operator_str]

    result = operator(number1, number2)

    print(f'number1 operator_str number2 = result')


    which you can put behing a if __name__ == '__main__'-guard



    if __name__ == '__main__':
    main()





    share|improve this answer



























      up vote
      7
      down vote













      sum



      you use sum as a variable name, shadowing the builtin, which is generally a bad idea



      function



      Divide the program into functions with their own goal. Here you have following part



      1. get the 2 numbers

      2. get the operation

      3. do the calculation

      4. present the result

      Get the numbers



      you ask for an input, which you get returned as a str. You convert this to a number with int. If the input is not an integer value, this will crash the program, so you'll need some sort of input validation.



      For the input validation, I will borrow a bit from this answer to another question



      def ask_number(message='please enter a number', number_types=None):
      if number_types is None:
      number_types = (int, float, complex)
      while True:
      number = input(message)
      for converter in number_types:
      try:
      return converter(number)
      except ValueError:
      pass
      else:
      print('Please enter a valid number')


      In this way, you can specify which types are valid, and in which order they should be tried. You can even use custom types if you want.



      This will keep asking until you have a valid number, and can be stopped with ctrl+c, which will raise a KeyboardInteruptError



      Get the operation



      To make it easy for ourselves, we define the default options for operators



      DEFAULT_OPERATIONS = 
      '+': operator.add,
      '-': operator.sub,
      '*': operator.mul,
      '//': operator.floordiv,
      '/': operator.truediv,
      '**': operator.pow,
      '^': operator.pow,



      This way we can call the function without arguments most of the times



      def ask_operator(operators=None):
      if operators is None:
      operators = DEFAULT_OPERATIONS

      message = f'Please select an operator from [','.join(map(str, operators)))]'
      while True:
      operator = input(message)
      if operator in operators:
      return operator
      else:
      print('Please enter a valid operator')


      putting it together



      def main():
      operators = DEFAULT_OPERATIONS

      number1 = ask_number('Please enter the first number:')
      number2 = ask_number('Please enter the second number:')
      operator_str = ask_operator(operators)
      operator = operators[operator_str]

      result = operator(number1, number2)

      print(f'number1 operator_str number2 = result')


      which you can put behing a if __name__ == '__main__'-guard



      if __name__ == '__main__':
      main()





      share|improve this answer

























        up vote
        7
        down vote










        up vote
        7
        down vote









        sum



        you use sum as a variable name, shadowing the builtin, which is generally a bad idea



        function



        Divide the program into functions with their own goal. Here you have following part



        1. get the 2 numbers

        2. get the operation

        3. do the calculation

        4. present the result

        Get the numbers



        you ask for an input, which you get returned as a str. You convert this to a number with int. If the input is not an integer value, this will crash the program, so you'll need some sort of input validation.



        For the input validation, I will borrow a bit from this answer to another question



        def ask_number(message='please enter a number', number_types=None):
        if number_types is None:
        number_types = (int, float, complex)
        while True:
        number = input(message)
        for converter in number_types:
        try:
        return converter(number)
        except ValueError:
        pass
        else:
        print('Please enter a valid number')


        In this way, you can specify which types are valid, and in which order they should be tried. You can even use custom types if you want.



        This will keep asking until you have a valid number, and can be stopped with ctrl+c, which will raise a KeyboardInteruptError



        Get the operation



        To make it easy for ourselves, we define the default options for operators



        DEFAULT_OPERATIONS = 
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '//': operator.floordiv,
        '/': operator.truediv,
        '**': operator.pow,
        '^': operator.pow,



        This way we can call the function without arguments most of the times



        def ask_operator(operators=None):
        if operators is None:
        operators = DEFAULT_OPERATIONS

        message = f'Please select an operator from [','.join(map(str, operators)))]'
        while True:
        operator = input(message)
        if operator in operators:
        return operator
        else:
        print('Please enter a valid operator')


        putting it together



        def main():
        operators = DEFAULT_OPERATIONS

        number1 = ask_number('Please enter the first number:')
        number2 = ask_number('Please enter the second number:')
        operator_str = ask_operator(operators)
        operator = operators[operator_str]

        result = operator(number1, number2)

        print(f'number1 operator_str number2 = result')


        which you can put behing a if __name__ == '__main__'-guard



        if __name__ == '__main__':
        main()





        share|improve this answer















        sum



        you use sum as a variable name, shadowing the builtin, which is generally a bad idea



        function



        Divide the program into functions with their own goal. Here you have following part



        1. get the 2 numbers

        2. get the operation

        3. do the calculation

        4. present the result

        Get the numbers



        you ask for an input, which you get returned as a str. You convert this to a number with int. If the input is not an integer value, this will crash the program, so you'll need some sort of input validation.



        For the input validation, I will borrow a bit from this answer to another question



        def ask_number(message='please enter a number', number_types=None):
        if number_types is None:
        number_types = (int, float, complex)
        while True:
        number = input(message)
        for converter in number_types:
        try:
        return converter(number)
        except ValueError:
        pass
        else:
        print('Please enter a valid number')


        In this way, you can specify which types are valid, and in which order they should be tried. You can even use custom types if you want.



        This will keep asking until you have a valid number, and can be stopped with ctrl+c, which will raise a KeyboardInteruptError



        Get the operation



        To make it easy for ourselves, we define the default options for operators



        DEFAULT_OPERATIONS = 
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '//': operator.floordiv,
        '/': operator.truediv,
        '**': operator.pow,
        '^': operator.pow,



        This way we can call the function without arguments most of the times



        def ask_operator(operators=None):
        if operators is None:
        operators = DEFAULT_OPERATIONS

        message = f'Please select an operator from [','.join(map(str, operators)))]'
        while True:
        operator = input(message)
        if operator in operators:
        return operator
        else:
        print('Please enter a valid operator')


        putting it together



        def main():
        operators = DEFAULT_OPERATIONS

        number1 = ask_number('Please enter the first number:')
        number2 = ask_number('Please enter the second number:')
        operator_str = ask_operator(operators)
        operator = operators[operator_str]

        result = operator(number1, number2)

        print(f'number1 operator_str number2 = result')


        which you can put behing a if __name__ == '__main__'-guard



        if __name__ == '__main__':
        main()






        share|improve this answer















        share|improve this answer



        share|improve this answer








        edited Jun 21 at 12:23









        Mathias Ettinger

        21.7k32875




        21.7k32875











        answered Jun 21 at 12:01









        Maarten Fabré

        3,204214




        3,204214




















            up vote
            -3
            down vote













            You could use the exec function if you wanted, which takes a string formatted as python code and runs the code that the string represents. After the first three lines, just type:



            exec('sum = number1' + operation + 'number2')
            print(sum)


            You would also want to use an if statement to make sure "operation" is actually an operation before running the above lines, though. You don't want your user to type in something crazy and crash the program.






            share|improve this answer

















            • 2




              "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
              – Mast
              Jun 21 at 19:29






            • 3




              Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
              – Hosch250
              Jun 21 at 19:43














            up vote
            -3
            down vote













            You could use the exec function if you wanted, which takes a string formatted as python code and runs the code that the string represents. After the first three lines, just type:



            exec('sum = number1' + operation + 'number2')
            print(sum)


            You would also want to use an if statement to make sure "operation" is actually an operation before running the above lines, though. You don't want your user to type in something crazy and crash the program.






            share|improve this answer

















            • 2




              "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
              – Mast
              Jun 21 at 19:29






            • 3




              Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
              – Hosch250
              Jun 21 at 19:43












            up vote
            -3
            down vote










            up vote
            -3
            down vote









            You could use the exec function if you wanted, which takes a string formatted as python code and runs the code that the string represents. After the first three lines, just type:



            exec('sum = number1' + operation + 'number2')
            print(sum)


            You would also want to use an if statement to make sure "operation" is actually an operation before running the above lines, though. You don't want your user to type in something crazy and crash the program.






            share|improve this answer













            You could use the exec function if you wanted, which takes a string formatted as python code and runs the code that the string represents. After the first three lines, just type:



            exec('sum = number1' + operation + 'number2')
            print(sum)


            You would also want to use an if statement to make sure "operation" is actually an operation before running the above lines, though. You don't want your user to type in something crazy and crash the program.







            share|improve this answer













            share|improve this answer



            share|improve this answer











            answered Jun 21 at 18:17









            noopygbhat

            112




            112







            • 2




              "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
              – Mast
              Jun 21 at 19:29






            • 3




              Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
              – Hosch250
              Jun 21 at 19:43












            • 2




              "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
              – Mast
              Jun 21 at 19:29






            • 3




              Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
              – Hosch250
              Jun 21 at 19:43







            2




            2




            "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
            – Mast
            Jun 21 at 19:29




            "You don't want your user to type in something crazy and crash the program." That's not the only problem either. I can probably whipe the harddrive of my computer by inputting the (exact) wrong operation. Isn't exec just as bloody dangerous as eval?
            – Mast
            Jun 21 at 19:29




            3




            3




            Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
            – Hosch250
            Jun 21 at 19:43




            Sorry, but I have to downvote for the suggestion to use exec. That is a firable offense in my book.
            – Hosch250
            Jun 21 at 19:43












             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196961%2fbasic-calculator-in-python%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Greedy Best First Search implementation in Rust

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            C++11 CLH Lock Implementation