-3

Does anyone know how to calculate directly from only one user input? for example:

input = 1 + 2
output = 3

only one input is allowed. Also, when the user enters an invalid equation such as 1 +* 2, it need to show invalid.

4131313513
  • 15
  • 4
  • 3
    "I've tried all day", Please share your code, your efforts in the post [edit] and add it – azro May 20 '21 at 12:20
  • Welcome to Stack Overflow? Have you tried searching on here for similar questions? Also are you looking to support only expressions with two numbers and an operator, or more complex inputs as well? – CrazyChucky May 20 '21 at 12:23
  • It sound interesting. I'll try – Rishabh Semwal May 20 '21 at 12:25
  • @CrazyChucky I tried to search for a similar question on Stack Overflow but none of them is using python language. I am new to programming so I can't understand the other language. The equation is a maximum of only 2 numbers. For example: 21 + 11, -21 - -11, -21 / 11, 21 * -11/ – 4131313513 May 20 '21 at 12:27
  • You can search for Python questions by putting `[python]` in your query. – CrazyChucky May 20 '21 at 12:33
  • 1
    Does this answer your question? [Evaluating a mathematical expression without eval() on Python3](https://stackoverflow.com/questions/38860682/evaluating-a-mathematical-expression-without-eval-on-python3) – TheEagle May 20 '21 at 14:28
  • @CrazyChucky in fact, this has already been asked before : https://stackoverflow.com/questions/38860682/evaluating-a-mathematical-expression-without-eval-on-python3 – TheEagle May 20 '21 at 14:29

1 Answers1

3

One of the ways is to use the eval() function.

user_input = input("Enter expression :")
try:
    print(eval(user_input))
except:
    print("Invalid expression!")

Example Output :

Enter expression : 1 + 2
>>> 3

But be wary of this function, as it could be dangerous to use in a few cases.

CoolCoder
  • 786
  • 7
  • 20