Python program for a simple calculatorFinding the lowest terms for fractions in C#TDD: String Calculator KataN-Bonnaci sequence calculatorTiny calculator using dependency injection and inversion of controlA simple pocket calculatorPseudo Random Number GeneratorJavaScript OOP calculatorComputing the total property management fee for propertiesMultiplying/Dividing before Adding/SubtractingA Java Calculator that could perform basic Mathematical Operations

SQL counting distinct over partition

Active low-pass filters --- good to what frequencies?

A IP can traceroute to it, but can not ping

Does a scale have more than seven chords?

Can Rydberg constant be in joules?

Why didn't Voldemort recognize that Dumbledore was affected by his curse?

What to do when surprise and a high initiative roll conflict with the narrative?

Fixing obscure 8080 emulator bug?

How is water heavier than petrol, even though its molecular weight is less than petrol?

Why can my keyboard only digest 6 keypresses at a time?

Does Disney no longer produce hand-drawn cartoon films?

I have a problem assistant manager, but I can't fire him

What ways have you found to get edits from non-LaTeX users?

is it possible for a vehicle to be manufactured witout a catalitic converter

How to communicate to my GM that not being allowed to use stealth isn't fun for me?

English word for "product of tinkering"

How come the nude protesters were not arrested?

Winning Strategy for the Magician and his Apprentice

How to handle self harm scars on the arm in work environment?

How to manually rewind film?

Playing a Character as Unobtrusive and Subservient, Yet Not Passive

Teaching a class likely meant to inflate the GPA of student athletes

Does the Long March-11 increase its thrust after clearing the launch tower?

How can this tool find out registered domains from an IP?



Python program for a simple calculator


Finding the lowest terms for fractions in C#TDD: String Calculator KataN-Bonnaci sequence calculatorTiny calculator using dependency injection and inversion of controlA simple pocket calculatorPseudo Random Number GeneratorJavaScript OOP calculatorComputing the total property management fee for propertiesMultiplying/Dividing before Adding/SubtractingA Java Calculator that could perform basic Mathematical Operations






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








4












$begingroup$


I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.



Here is my code:



# This function adds two numbers 
def add(x, y):
return x + y

# This function subtracts two numbers
def subtract(x, y):
return x - y

# This function multiplies two numbers
def multiply(x, y):
return x * y

# This function divides two numbers
def divide(x, y):
return x / y

print ("Select operation.")
print ("1. Add")
print ("2. Subtract")
print ("3. Multiply")
print ("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1,num2))

elif choice == '2':
print(num1, "-", num2, "=", subtract(num1,num2))

elif choice == '3':
print(num1, "*", num2, "=", multiply(num1,num2))

elif choice == '4':
print(num1, "/", num2, "=", divide(num1,num2))
else:
print("Invalid input")


So, I would like to know whether I could make this code shorter and more efficient.



Also, any alternatives are greatly welcome.



Any help would be highly appreciated.










share|improve this question











$endgroup$


















    4












    $begingroup$


    I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.



    Here is my code:



    # This function adds two numbers 
    def add(x, y):
    return x + y

    # This function subtracts two numbers
    def subtract(x, y):
    return x - y

    # This function multiplies two numbers
    def multiply(x, y):
    return x * y

    # This function divides two numbers
    def divide(x, y):
    return x / y

    print ("Select operation.")
    print ("1. Add")
    print ("2. Subtract")
    print ("3. Multiply")
    print ("4. Divide")

    choice = input("Enter choice (1/2/3/4): ")

    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if choice == '1':
    print(num1, "+", num2, "=", add(num1,num2))

    elif choice == '2':
    print(num1, "-", num2, "=", subtract(num1,num2))

    elif choice == '3':
    print(num1, "*", num2, "=", multiply(num1,num2))

    elif choice == '4':
    print(num1, "/", num2, "=", divide(num1,num2))
    else:
    print("Invalid input")


    So, I would like to know whether I could make this code shorter and more efficient.



    Also, any alternatives are greatly welcome.



    Any help would be highly appreciated.










    share|improve this question











    $endgroup$














      4












      4








      4


      1



      $begingroup$


      I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.



      Here is my code:



      # This function adds two numbers 
      def add(x, y):
      return x + y

      # This function subtracts two numbers
      def subtract(x, y):
      return x - y

      # This function multiplies two numbers
      def multiply(x, y):
      return x * y

      # This function divides two numbers
      def divide(x, y):
      return x / y

      print ("Select operation.")
      print ("1. Add")
      print ("2. Subtract")
      print ("3. Multiply")
      print ("4. Divide")

      choice = input("Enter choice (1/2/3/4): ")

      num1 = int(input("Enter first number: "))
      num2 = int(input("Enter second number: "))

      if choice == '1':
      print(num1, "+", num2, "=", add(num1,num2))

      elif choice == '2':
      print(num1, "-", num2, "=", subtract(num1,num2))

      elif choice == '3':
      print(num1, "*", num2, "=", multiply(num1,num2))

      elif choice == '4':
      print(num1, "/", num2, "=", divide(num1,num2))
      else:
      print("Invalid input")


      So, I would like to know whether I could make this code shorter and more efficient.



      Also, any alternatives are greatly welcome.



      Any help would be highly appreciated.










      share|improve this question











      $endgroup$




      I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.



      Here is my code:



      # This function adds two numbers 
      def add(x, y):
      return x + y

      # This function subtracts two numbers
      def subtract(x, y):
      return x - y

      # This function multiplies two numbers
      def multiply(x, y):
      return x * y

      # This function divides two numbers
      def divide(x, y):
      return x / y

      print ("Select operation.")
      print ("1. Add")
      print ("2. Subtract")
      print ("3. Multiply")
      print ("4. Divide")

      choice = input("Enter choice (1/2/3/4): ")

      num1 = int(input("Enter first number: "))
      num2 = int(input("Enter second number: "))

      if choice == '1':
      print(num1, "+", num2, "=", add(num1,num2))

      elif choice == '2':
      print(num1, "-", num2, "=", subtract(num1,num2))

      elif choice == '3':
      print(num1, "*", num2, "=", multiply(num1,num2))

      elif choice == '4':
      print(num1, "/", num2, "=", divide(num1,num2))
      else:
      print("Invalid input")


      So, I would like to know whether I could make this code shorter and more efficient.



      Also, any alternatives are greatly welcome.



      Any help would be highly appreciated.







      python performance python-3.x calculator






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 22 at 16:16









      Mast

      7,80363790




      7,80363790










      asked May 22 at 14:04









      JustinJustin

      1,318427




      1,318427




















          3 Answers
          3






          active

          oldest

          votes


















          7












          $begingroup$

          1. You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.


          2. You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).


          Here is the improved code:



          # This function adds two numbers 
          def add(x, y):
          return x + y

          # This function subtracts two numbers
          def subtract(x, y):
          return x - y

          # This function multiplies two numbers
          def multiply(x, y):
          return x * y

          # This function divides two numbers
          def divide(x, y):
          return x / y

          print("Select operation.")
          print("1. Add")
          print("2. Subtract")
          print("3. Multiply")
          print("4. Divide")

          functions_dict =
          '1': [add, '+'],
          '2': [subtract, '-'],
          '3': [multiply, '*'],
          '4': [divide, '/']


          while True:
          choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
          if choice == 'q':
          break
          elif choice in functions_dict:
          num1 = int(input("Enter first number: "))
          num2 = int(input("Enter second number: "))
          print(' = '.format(
          num1,
          functions_dict[choice][1],
          num2,
          functions_dict[choice][0](num1, num2)
          ))
          else:
          print('Invalid number')






          share|improve this answer











          $endgroup$












          • $begingroup$
            I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
            $endgroup$
            – perennial_noob
            May 22 at 20:54










          • $begingroup$
            Maybe add print ("Q. Quit") after print ("4. Divide")
            $endgroup$
            – Stobor
            May 23 at 1:55






          • 1




            $begingroup$
            A few things: There should be no space after the print function. You can also use elif choice in functions_dict
            $endgroup$
            – Ben
            May 23 at 12:42










          • $begingroup$
            Thank you! elif choice in functions_dict is really better than my version.
            $endgroup$
            – vurmux
            May 23 at 13:13










          • $begingroup$
            No if main guard?
            $endgroup$
            – D. Ben Knoble
            May 23 at 15:38


















          6












          $begingroup$

          One issue I see is with casting the user's input to int:



          num1 = int(input("Enter first number: "))
          num2 = int(input("Enter second number: "))


          You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.



          I suggest either surrounding the input with a try/except block to catch that possibility:



          try:
          num1 = int(input("Enter first number: "))
          except ValueError:
          print("RuhRoh")


          Or using str.isdigit():



          num1 = input("Enter first number: ")
          if not num1.isdigit():
          print("RuhRoh")





          share|improve this answer









          $endgroup$




















            1












            $begingroup$

            I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.



            Hopefully this code will show you about regex and such. Findall is quite useful.



             import re
            while True:
            my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
            if not my_operation:
            print("Goodbye!")
            break
            numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
            if len(numstrings) == 1:
            print("I need an operation.")
            continue
            if len(numstrings) != 2: #2*3*4 bails
            print("I can only do a single operation right now.")
            continue
            for my_num in numstrings:
            if not my_num.isdigit(): #e.g. if you try z * 12
            print(my_num, "is not a digit.")
            continue
            numbers = [int(x) for x in numstrings] # convert strings to integers
            my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
            out_string = my_operation + " = "
            if my_operator == '-': out_string += str(numbers[0] - numbers[1])
            elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
            elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
            elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
            else: print("unknown")
            print(out_string)


            Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).






            share|improve this answer









            $endgroup$













              Your Answer






              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',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              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%2f220732%2fpython-program-for-a-simple-calculator%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              7












              $begingroup$

              1. You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.


              2. You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).


              Here is the improved code:



              # This function adds two numbers 
              def add(x, y):
              return x + y

              # This function subtracts two numbers
              def subtract(x, y):
              return x - y

              # This function multiplies two numbers
              def multiply(x, y):
              return x * y

              # This function divides two numbers
              def divide(x, y):
              return x / y

              print("Select operation.")
              print("1. Add")
              print("2. Subtract")
              print("3. Multiply")
              print("4. Divide")

              functions_dict =
              '1': [add, '+'],
              '2': [subtract, '-'],
              '3': [multiply, '*'],
              '4': [divide, '/']


              while True:
              choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
              if choice == 'q':
              break
              elif choice in functions_dict:
              num1 = int(input("Enter first number: "))
              num2 = int(input("Enter second number: "))
              print(' = '.format(
              num1,
              functions_dict[choice][1],
              num2,
              functions_dict[choice][0](num1, num2)
              ))
              else:
              print('Invalid number')






              share|improve this answer











              $endgroup$












              • $begingroup$
                I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
                $endgroup$
                – perennial_noob
                May 22 at 20:54










              • $begingroup$
                Maybe add print ("Q. Quit") after print ("4. Divide")
                $endgroup$
                – Stobor
                May 23 at 1:55






              • 1




                $begingroup$
                A few things: There should be no space after the print function. You can also use elif choice in functions_dict
                $endgroup$
                – Ben
                May 23 at 12:42










              • $begingroup$
                Thank you! elif choice in functions_dict is really better than my version.
                $endgroup$
                – vurmux
                May 23 at 13:13










              • $begingroup$
                No if main guard?
                $endgroup$
                – D. Ben Knoble
                May 23 at 15:38















              7












              $begingroup$

              1. You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.


              2. You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).


              Here is the improved code:



              # This function adds two numbers 
              def add(x, y):
              return x + y

              # This function subtracts two numbers
              def subtract(x, y):
              return x - y

              # This function multiplies two numbers
              def multiply(x, y):
              return x * y

              # This function divides two numbers
              def divide(x, y):
              return x / y

              print("Select operation.")
              print("1. Add")
              print("2. Subtract")
              print("3. Multiply")
              print("4. Divide")

              functions_dict =
              '1': [add, '+'],
              '2': [subtract, '-'],
              '3': [multiply, '*'],
              '4': [divide, '/']


              while True:
              choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
              if choice == 'q':
              break
              elif choice in functions_dict:
              num1 = int(input("Enter first number: "))
              num2 = int(input("Enter second number: "))
              print(' = '.format(
              num1,
              functions_dict[choice][1],
              num2,
              functions_dict[choice][0](num1, num2)
              ))
              else:
              print('Invalid number')






              share|improve this answer











              $endgroup$












              • $begingroup$
                I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
                $endgroup$
                – perennial_noob
                May 22 at 20:54










              • $begingroup$
                Maybe add print ("Q. Quit") after print ("4. Divide")
                $endgroup$
                – Stobor
                May 23 at 1:55






              • 1




                $begingroup$
                A few things: There should be no space after the print function. You can also use elif choice in functions_dict
                $endgroup$
                – Ben
                May 23 at 12:42










              • $begingroup$
                Thank you! elif choice in functions_dict is really better than my version.
                $endgroup$
                – vurmux
                May 23 at 13:13










              • $begingroup$
                No if main guard?
                $endgroup$
                – D. Ben Knoble
                May 23 at 15:38













              7












              7








              7





              $begingroup$

              1. You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.


              2. You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).


              Here is the improved code:



              # This function adds two numbers 
              def add(x, y):
              return x + y

              # This function subtracts two numbers
              def subtract(x, y):
              return x - y

              # This function multiplies two numbers
              def multiply(x, y):
              return x * y

              # This function divides two numbers
              def divide(x, y):
              return x / y

              print("Select operation.")
              print("1. Add")
              print("2. Subtract")
              print("3. Multiply")
              print("4. Divide")

              functions_dict =
              '1': [add, '+'],
              '2': [subtract, '-'],
              '3': [multiply, '*'],
              '4': [divide, '/']


              while True:
              choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
              if choice == 'q':
              break
              elif choice in functions_dict:
              num1 = int(input("Enter first number: "))
              num2 = int(input("Enter second number: "))
              print(' = '.format(
              num1,
              functions_dict[choice][1],
              num2,
              functions_dict[choice][0](num1, num2)
              ))
              else:
              print('Invalid number')






              share|improve this answer











              $endgroup$



              1. You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.


              2. You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).


              Here is the improved code:



              # This function adds two numbers 
              def add(x, y):
              return x + y

              # This function subtracts two numbers
              def subtract(x, y):
              return x - y

              # This function multiplies two numbers
              def multiply(x, y):
              return x * y

              # This function divides two numbers
              def divide(x, y):
              return x / y

              print("Select operation.")
              print("1. Add")
              print("2. Subtract")
              print("3. Multiply")
              print("4. Divide")

              functions_dict =
              '1': [add, '+'],
              '2': [subtract, '-'],
              '3': [multiply, '*'],
              '4': [divide, '/']


              while True:
              choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
              if choice == 'q':
              break
              elif choice in functions_dict:
              num1 = int(input("Enter first number: "))
              num2 = int(input("Enter second number: "))
              print(' = '.format(
              num1,
              functions_dict[choice][1],
              num2,
              functions_dict[choice][0](num1, num2)
              ))
              else:
              print('Invalid number')







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 at 13:14

























              answered May 22 at 14:32









              vurmuxvurmux

              1,225214




              1,225214











              • $begingroup$
                I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
                $endgroup$
                – perennial_noob
                May 22 at 20:54










              • $begingroup$
                Maybe add print ("Q. Quit") after print ("4. Divide")
                $endgroup$
                – Stobor
                May 23 at 1:55






              • 1




                $begingroup$
                A few things: There should be no space after the print function. You can also use elif choice in functions_dict
                $endgroup$
                – Ben
                May 23 at 12:42










              • $begingroup$
                Thank you! elif choice in functions_dict is really better than my version.
                $endgroup$
                – vurmux
                May 23 at 13:13










              • $begingroup$
                No if main guard?
                $endgroup$
                – D. Ben Knoble
                May 23 at 15:38
















              • $begingroup$
                I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
                $endgroup$
                – perennial_noob
                May 22 at 20:54










              • $begingroup$
                Maybe add print ("Q. Quit") after print ("4. Divide")
                $endgroup$
                – Stobor
                May 23 at 1:55






              • 1




                $begingroup$
                A few things: There should be no space after the print function. You can also use elif choice in functions_dict
                $endgroup$
                – Ben
                May 23 at 12:42










              • $begingroup$
                Thank you! elif choice in functions_dict is really better than my version.
                $endgroup$
                – vurmux
                May 23 at 13:13










              • $begingroup$
                No if main guard?
                $endgroup$
                – D. Ben Knoble
                May 23 at 15:38















              $begingroup$
              I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
              $endgroup$
              – perennial_noob
              May 22 at 20:54




              $begingroup$
              I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
              $endgroup$
              – perennial_noob
              May 22 at 20:54












              $begingroup$
              Maybe add print ("Q. Quit") after print ("4. Divide")
              $endgroup$
              – Stobor
              May 23 at 1:55




              $begingroup$
              Maybe add print ("Q. Quit") after print ("4. Divide")
              $endgroup$
              – Stobor
              May 23 at 1:55




              1




              1




              $begingroup$
              A few things: There should be no space after the print function. You can also use elif choice in functions_dict
              $endgroup$
              – Ben
              May 23 at 12:42




              $begingroup$
              A few things: There should be no space after the print function. You can also use elif choice in functions_dict
              $endgroup$
              – Ben
              May 23 at 12:42












              $begingroup$
              Thank you! elif choice in functions_dict is really better than my version.
              $endgroup$
              – vurmux
              May 23 at 13:13




              $begingroup$
              Thank you! elif choice in functions_dict is really better than my version.
              $endgroup$
              – vurmux
              May 23 at 13:13












              $begingroup$
              No if main guard?
              $endgroup$
              – D. Ben Knoble
              May 23 at 15:38




              $begingroup$
              No if main guard?
              $endgroup$
              – D. Ben Knoble
              May 23 at 15:38













              6












              $begingroup$

              One issue I see is with casting the user's input to int:



              num1 = int(input("Enter first number: "))
              num2 = int(input("Enter second number: "))


              You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.



              I suggest either surrounding the input with a try/except block to catch that possibility:



              try:
              num1 = int(input("Enter first number: "))
              except ValueError:
              print("RuhRoh")


              Or using str.isdigit():



              num1 = input("Enter first number: ")
              if not num1.isdigit():
              print("RuhRoh")





              share|improve this answer









              $endgroup$

















                6












                $begingroup$

                One issue I see is with casting the user's input to int:



                num1 = int(input("Enter first number: "))
                num2 = int(input("Enter second number: "))


                You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.



                I suggest either surrounding the input with a try/except block to catch that possibility:



                try:
                num1 = int(input("Enter first number: "))
                except ValueError:
                print("RuhRoh")


                Or using str.isdigit():



                num1 = input("Enter first number: ")
                if not num1.isdigit():
                print("RuhRoh")





                share|improve this answer









                $endgroup$















                  6












                  6








                  6





                  $begingroup$

                  One issue I see is with casting the user's input to int:



                  num1 = int(input("Enter first number: "))
                  num2 = int(input("Enter second number: "))


                  You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.



                  I suggest either surrounding the input with a try/except block to catch that possibility:



                  try:
                  num1 = int(input("Enter first number: "))
                  except ValueError:
                  print("RuhRoh")


                  Or using str.isdigit():



                  num1 = input("Enter first number: ")
                  if not num1.isdigit():
                  print("RuhRoh")





                  share|improve this answer









                  $endgroup$



                  One issue I see is with casting the user's input to int:



                  num1 = int(input("Enter first number: "))
                  num2 = int(input("Enter second number: "))


                  You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.



                  I suggest either surrounding the input with a try/except block to catch that possibility:



                  try:
                  num1 = int(input("Enter first number: "))
                  except ValueError:
                  print("RuhRoh")


                  Or using str.isdigit():



                  num1 = input("Enter first number: ")
                  if not num1.isdigit():
                  print("RuhRoh")






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 22 at 14:33









                  Clay RecordsClay Records

                  1613




                  1613





















                      1












                      $begingroup$

                      I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.



                      Hopefully this code will show you about regex and such. Findall is quite useful.



                       import re
                      while True:
                      my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
                      if not my_operation:
                      print("Goodbye!")
                      break
                      numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
                      if len(numstrings) == 1:
                      print("I need an operation.")
                      continue
                      if len(numstrings) != 2: #2*3*4 bails
                      print("I can only do a single operation right now.")
                      continue
                      for my_num in numstrings:
                      if not my_num.isdigit(): #e.g. if you try z * 12
                      print(my_num, "is not a digit.")
                      continue
                      numbers = [int(x) for x in numstrings] # convert strings to integers
                      my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
                      out_string = my_operation + " = "
                      if my_operator == '-': out_string += str(numbers[0] - numbers[1])
                      elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
                      elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
                      elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
                      else: print("unknown")
                      print(out_string)


                      Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).






                      share|improve this answer









                      $endgroup$

















                        1












                        $begingroup$

                        I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.



                        Hopefully this code will show you about regex and such. Findall is quite useful.



                         import re
                        while True:
                        my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
                        if not my_operation:
                        print("Goodbye!")
                        break
                        numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
                        if len(numstrings) == 1:
                        print("I need an operation.")
                        continue
                        if len(numstrings) != 2: #2*3*4 bails
                        print("I can only do a single operation right now.")
                        continue
                        for my_num in numstrings:
                        if not my_num.isdigit(): #e.g. if you try z * 12
                        print(my_num, "is not a digit.")
                        continue
                        numbers = [int(x) for x in numstrings] # convert strings to integers
                        my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
                        out_string = my_operation + " = "
                        if my_operator == '-': out_string += str(numbers[0] - numbers[1])
                        elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
                        elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
                        elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
                        else: print("unknown")
                        print(out_string)


                        Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).






                        share|improve this answer









                        $endgroup$















                          1












                          1








                          1





                          $begingroup$

                          I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.



                          Hopefully this code will show you about regex and such. Findall is quite useful.



                           import re
                          while True:
                          my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
                          if not my_operation:
                          print("Goodbye!")
                          break
                          numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
                          if len(numstrings) == 1:
                          print("I need an operation.")
                          continue
                          if len(numstrings) != 2: #2*3*4 bails
                          print("I can only do a single operation right now.")
                          continue
                          for my_num in numstrings:
                          if not my_num.isdigit(): #e.g. if you try z * 12
                          print(my_num, "is not a digit.")
                          continue
                          numbers = [int(x) for x in numstrings] # convert strings to integers
                          my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
                          out_string = my_operation + " = "
                          if my_operator == '-': out_string += str(numbers[0] - numbers[1])
                          elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
                          elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
                          elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
                          else: print("unknown")
                          print(out_string)


                          Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).






                          share|improve this answer









                          $endgroup$



                          I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.



                          Hopefully this code will show you about regex and such. Findall is quite useful.



                           import re
                          while True:
                          my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
                          if not my_operation:
                          print("Goodbye!")
                          break
                          numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
                          if len(numstrings) == 1:
                          print("I need an operation.")
                          continue
                          if len(numstrings) != 2: #2*3*4 bails
                          print("I can only do a single operation right now.")
                          continue
                          for my_num in numstrings:
                          if not my_num.isdigit(): #e.g. if you try z * 12
                          print(my_num, "is not a digit.")
                          continue
                          numbers = [int(x) for x in numstrings] # convert strings to integers
                          my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
                          out_string = my_operation + " = "
                          if my_operator == '-': out_string += str(numbers[0] - numbers[1])
                          elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
                          elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
                          elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
                          else: print("unknown")
                          print(out_string)


                          Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered May 23 at 13:14









                          aschultzaschultz

                          1731211




                          1731211



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220732%2fpython-program-for-a-simple-calculator%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

                              Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

                              What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company