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)
2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I wanted to practice how to end the calculation if user enter a 'c'.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.