-3

This is the code I have at the moment:

print "What equation would you like"
a = raw_input()
print "What's", a
b = input()
print a == b

I want to prompt a user to enter a maths equation, for example 3+4.

I’ve been trying to convert this to Python 3 by using input(), however, since input() would actually solve the equation, the next line underneath would print the answer to equation like this: What's 7.

Since the idea is trying to solve the equation inputed for variable a, the entire idea of the code is meaningless as they could literally type in 7 and the next line would print out True because 7 == 7.

Is there any way that I can type in an equation like 3+4 and actually output What's 3+4 without Python telling me that the end result is False?

Oh and in regards to: Math operations from string, I actually did see that post before posting this question and what it looked like is basically getting python to output an answer to an equation which went entirely against what I was trying to achieve. Instead, I wanted python just to tell me whether the answer which I had typed in was correct or incorrect, hence true and false.

In regards to my previous post, it was simply meant to be about answering an equation which I manually put in the script. However, since I wanted to ask a user to type in a maths equation in the new script, the method used previously wouldn't work.

I also tried ast.literal_eval(), but I got this error...

Traceback (most recent call last):
File "/tmp/KANTL/Math.py", line 7, in <module>
print literal_eval(a) == literal_eval(b)
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
  • 1
    Have you tried using `raw_input()` for `a`? – TigerhawkT3 Apr 09 '16 at 07:31
  • In response to Tigerhawk - Yes, it still tells me False for 'print a == b' – Joshua Stokes Apr 09 '16 at 07:34
  • Are you expecting to get two expressions, display them as they are, and then evaluate them and compare for equality? – TigerhawkT3 Apr 09 '16 at 07:35
  • 4
    Maybe try a search next time before you ask: http://stackoverflow.com/questions/9685946/math-operations-from-string – tfv Apr 09 '16 at 07:40
  • Pocket calculators are basically `eval()` machines, which makes emulating them with a powerful programming language on a PC pretty difficult to do safely. Pocket calculators don't have full keyboards, don't have modules for wiping your hard drive, can't distribute viruses, and so on. I'd recommend looking elsewhere for educational projects. Simple games like hangman are a good choice (text-based RPGs aren't ideal, as they have a tendency to bog the developer down in content and details, bloating the source code and making a mess). – TigerhawkT3 Apr 09 '16 at 07:47
  • Yeah, I guess it really just a fun experiment that I was trying out. – Joshua Stokes Apr 09 '16 at 07:50

3 Answers3

0

In Python 2, an expression of the form...

input(prompt)

Is equivalent to...

eval(raw_input(prompt))

The raw_input() built-in function reads a single line from sys.stdin and returns it, optionally with a prompt if given as argument. The eval() built-in function does a quite complex job, but for our purposes, it just takes a string an evaluates it as a Python expression.

So, you may want to do...

print "What equation would you like"
a = raw_input()
print "What's", a
b = raw_input()
print eval(a) == eval(b)

If your input can't be trusted, then try this instead...

from ast import literal_eval

And use literal_eval() where you would normally use eval(). The explanation is that eval() can do quite bad things if an attacker gets to know of its use. Seriously. Read the link for details. literal_eval() is designed to provide protection against this kind of security flaws.

Community
  • 1
  • 1
3442
  • 8,248
  • 2
  • 19
  • 41
-1

Using raw_input() for a and input() for b is probably what you're going for.

Testing this in the python interpreter gives the expected output:

>>> a = raw_input()
3+4
>>> a
'3+4'
>>> b = input()
7
>>> type(b)
<type 'int'>
>>> eval(a)
7

So you should be able to do something like this:

>>> eval(a) == b
true

EDIT:

After reading other user's responses, it appears the use of eval() is generally discouraged because of its potential dangers. Although for simple testing purposes you should be alright (if you intend to distribute this program or make it accessible from the web you should absolutely not use eval() ). Your code would look like this:

print "What equation would you like"
a = raw_input()
print "What's", a
b = input()
print eval(a) == b

Which should yield True with a correct solution and False with an incorrect solution.

MS-DDOS
  • 578
  • 5
  • 15
  • Typed this answer at the same time y'all. Relax with the down votes. – MS-DDOS Apr 09 '16 at 07:37
  • OP I've updated my answer per your comments......which now seem to be gone. I think this question has been more than sufficiently answered, so I'm out. – MS-DDOS Apr 09 '16 at 07:51
-1

Have you tried using eval?

print "What equation would you like"
a = raw_input()
print "What's", a
b = raw_input()
print eval(a) == eval(b)

As people consider eval to be evil (shouldn't be an issue in your case), the alternative is ast.literal_eval:

import ast.literal_eval as eval

Then use it as in the above example

smac89
  • 39,374
  • 15
  • 132
  • 179
  • `eval` is a very dangerous statement in this context. `ast.literal_eval` would be a wiser choice. – Selcuk Apr 09 '16 at 07:37
  • @Selcuk: I think that, for the OP's situation in particular, it's safe to use `eval` here. – 3442 Apr 09 '16 at 07:39
  • @KemyLand Actually this is exactly the case where you _shouldn't_ use `eval`. – Selcuk Apr 09 '16 at 07:40
  • @Selcuk, can you explain why eval is dangerous in this case? And by this case I mean, doing simple arithmetic – smac89 Apr 09 '16 at 07:41
  • No one can guarantee that the user will type in simple arithmetic equations to the prompt. It allows arbitrary Python code to be executed. See http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html for a few examples. – Selcuk Apr 09 '16 at 07:42
  • @Selcuk, OP will be running `1+1`, and such with eval. If eval cannot be used for such operations, then what is it's purpose? – smac89 Apr 09 '16 at 07:42
  • @Smac89: It's purpose is to use it on trusted input. Selcuk is right that it shouldn't be used on untrusted input. However, as the OP seems to be doing just a simple exercise, and we assume that the OP can trust him/herself, then `eval()` is most likely safe here. – 3442 Apr 09 '16 at 07:45
  • @Smac89 I don't want to go into detail because you should really read the article but `eval` is for places where you know what will be evaluated beforehand (such as hardcoded strings). If you accept user input, you should always be wary. This code might be running on a remote server where an attacker can easily delete files from it! – Selcuk Apr 09 '16 at 07:45
  • @Selcuk, OP can guarantee that he would not be deleting his entire OS with this. I think a better response would be to offer `ast.literal_eval` as a safer alternative with the dangers of `eval` explained rather than dismissing any thoughts of using `eval`. Heck I just used `eval` and I'm still fine. Btw the article you provided does not even focus on arithmetic which is not what OP is trying to do – smac89 Apr 09 '16 at 07:48
  • @Smac89: The dangers shown in the link are very real. There's code there that can crash **the Python interpreter itself**. – 3442 Apr 09 '16 at 07:49
  • @KemyLand, like I said, OP is not out to find code that crashes the python intepreter and therefore is very unlikely to type such code into eval. Arithmetic people, it's just math! – smac89 Apr 09 '16 at 07:51
  • @Smac89: That's exactly what I said just above. It's true, it's a bit of an exaggeration to take this measures in a simple test program. However, that doesn't mean that the OP should be used to rinse `eval()` like magic powder over every possible input-parsing problem. – 3442 Apr 09 '16 at 07:55
  • 4
    I would dismiss any thoughts of using `eval` when it is used to evaluate _external user input_, be it a toy project or a real one. This is my personal opinion on the subject. – Selcuk Apr 09 '16 at 07:59
  • Thanks everyone, I read all of your comments. Yes, this is simply a test excerise that I decided to do since I'm trying to learn Python. Obviously this means I won't be running this on a server and only I and maybe my friends will be using it, with me watching of course, not that they'd know how to cause malicious intent anyways. Also what's 'OP'? I've seen it being used a lot... – Joshua Stokes Apr 09 '16 at 12:31
  • Hey guys, just making another quick post on this in regards to my previous post. I found out that Op means 'original poster'... – Joshua Stokes Sep 25 '16 at 11:12