3

I want to let user enter string such as 2+5-3+6 and return 10. If user enter c then answer will be printed. I don't know how to make the project break when user enter a c.

print 'This is a calculator. Please follow the instruction.'

temp = 0
string = 0

def asmd(string):
    print 'Your answer is', eval(str(string))

while temp != 'c':
    print 'Please enter a number or operation. Enter c to complete. :'
    temp = raw_input()
    string = str(string)+str(temp)

    if temp == str('c'):
        asmd(string)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
hitheredude
  • 929
  • 5
  • 18
  • 32
  • 3
    `eval` is dangerous, it can easily be used to inject code into your script for undesired consequences. see http://stackoverflow.com/questions/1826859/is-there-ever-a-good-reason-to-use-eval?rq=1 – Inbar Rose Oct 18 '12 at 16:45
  • 6
    @InbarRose: Good article by Ned Batchelder on the topic: http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html – Joel Cornett Oct 18 '12 at 16:46

1 Answers1

1

To fix the calculator, just make sure the ending character (c) doesn't end up in your result string:

if temp == str('c'):
    asmd(string[:-1])

I have to note though that the whole script is pretty crazy. You are using eval, which can evaluate complete expressions at once, but still you instruct users to enter them one-by-one. With eval, you can rewrite your whole script in one line:

print eval(raw_input())

Also as extensively pointed out in the comments, it is generally bad idea to use eval in case you don't trust the user running your calculator. If you are just practising then fine -- just don't use eval in "real code".

jsalonen
  • 29,593
  • 15
  • 91
  • 109
  • Thanks. I wanted to practice how to end the calculation if user enter a 'c'. – hitheredude Oct 18 '12 at 16:57
  • Yeah. If so then you just need to remove the `c` character from your string as stated above. Otherwise you get like `1+2c` which has a syntax error. – jsalonen Oct 18 '12 at 16:58