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.
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.
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.