How can i build a calculator

Question:how can i build a working calculator

Replit Profile: https://replit.com/@akunreseller439

First, design it of course. Then, if you’re wondering how to do the calculations, you can use the eval function in JavaScript. It takes in a string and outputs the mathematical solution. Example:

const answerToTwoPlusTwo = eval("2 + 2") // 4

You can detect when your calculator buttons are clicked, and combine all of them into a string or array. Then when the user presses the equal sign, you can run eval and show them the result.

2 Likes

It looks like you are trying to build a calculator in python. (remember to include the language when asking questions.)
An easy way to do this is with the builtin eval function. It takes a string and evaluates it as if it is a python expression. It’s not perfect, but it works.

def calculate():
  inp = input().replace('^', '**')  # exponentiation in python uses **, double asterisk
  for character in inp:
    if character.isalpha():  # no alphabet letters allowed
      print('Invalid input')
      return
  try:
    result = eval(inp)
  except SyntaxError:  # bad input
    print('Invalid input')
    return
  print('The result is:', result)
3 Likes

@akunreseller439 You can use Python’s math module to run calculations too!

1 Like