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

                              Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                              Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                              Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020