-2

So I wanna make a code that solves simple problems (For example 3+4=? or 2/4+5=?) that are typed in by the user with input() but it treats the returned value as a string and it doesn't wanna work. Basicly I wanna do this correctly:

print('Enter a problem:')
equals = input()
print('The answer is {}.'.format(equals))

Thanks in advance and have a nice day!

4 Answers4

0

Well input() always returns a string. There is no way around that. However, you can't just "cast" it to be an equation. However, if you know the operations that will be inputted you can do some parsing. For example, this is how you might handle addition.

print('Enter a problem:')
equation = input() # user inputs 3+4=?

equalsIndex = equation.index('=')

# Reads the equation up to the equals symbol and splits the equation into the two numbers being added.
nums = equation[:equalsIndex].split('+')

nums[0] = int(nums[0])
nums[1] = int(nums[0])

print('The answer is {}.'.format(nums[0] + nums[1]))

In general, you would have to parse for the different operations.

Kevin
  • 121
  • 8
0

You can't transform this from "string" to "code". I think that exist a lot of libraries that can help you (example).

Other option is that you write your own code to do that. Main idea of that is to get numbers and operators from string to variables. You can use "if" to choosing operations.

Example. You have a input string in format "a+b" or "a-b", where a,b - integers from 1 to 9. You can take first and last symbol of that string. Convert it into integer and save into variables. Next step is check if second symbol of the string is "+" than you can add this two variables. Otherwise you can sub this variables. That's it.

Obviously if you want some powerful application you need more work, but it only an idea.

-1

To my experience, I have no idea on how to solve problem directly inside the input(). The only way to solve your issue (I think) is overide the input() method. You can Google 'overriding method python' and you'll find the syntax.

Hope you'll figure out this problem. Have a nice day :)

haydenp
  • 41
  • 2
-1

Use exec as follows.

equation = input("Input your equation")
exec("output = {}".format(equation))
print(output)

Here is an example (Note. "=" should not be included in the equation)

Input your equation: 2+4
6
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11