Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using eval() in python to add numbers

Tags:

python

eval

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)
like image 611
lavitanien Avatar asked Feb 22 '26 23:02

lavitanien


1 Answers

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

like image 109
jsalonen Avatar answered Feb 25 '26 13:02

jsalonen