Sunday, March 18, 2012

exercise 7.4 - eval_loop


"""====================
exercise 7.4
===================="""

import math

def eval_loop():
    #initialize variables
    input = ""
    last_input = ""
    
    #get user input from interpreter
    #until user types 'done'
    while True:
        print "your input, please :)"
        print "to end, type 'done'"
        input = raw_input()
        if input == 'done':
            return result
            break
        else:
            result = eval(input)
            print result
# end eval_loop()

return_result = eval_loop()
print "returned result = ", return_result

2 comments:

  1. Actually you don't need to end the function eval_loop().

    here is mine:

    def eval_loop():
    while True:
    calculation=raw_input("Please enter the calculation: ")
    try:
    if calculation=="done":
    print "The last result is",result
    print "Bye!"
    break
    except UnboundLocalError:
    print "none"
    break
    else:
    result=eval(calculation)
    print result

    Also, I expected the UnboundLocalError. It is when the program asks the user for the first time
    and you typed "done", it gives this error. I used this trick to correct it :)
    Sorry for the indentation issue, I couldn't correct it here.

    ReplyDelete
  2. def call():
    return str(input('Please enter something to evaluate: '))



    def eval_loop(x):
    x = call()
    while x != 'done':
    last_call = x
    if len(x) > 0:
    print(eval(x))
    x = call()
    else:
    print('You need to enter a string!')
    eval_loop(x)

    return last_call

    print(eval_loop(call))

    ReplyDelete

Note: Only a member of this blog may post a comment.