Python Forum

Full Version: Assigning a new value to variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I assign the result (res) of the calulation to the variable "memory" and then check if the user input is "M" and if so, then set
x or y = M
??

msg_0 = "Enter an equation"
msg_1 = "Do you even know what numbers are? Stay focused!"
msg_2 = "Yes ... an interesting math operation. You've slept through all classes, haven't you?"
msg_3 = "Yeah... division by zero. Smart move..."
msg_4 = "Do you want to store the result? (y / n):"
msg_5 = "Do you want to continue calculations? (y / n):"
oper = ['+', '-', '*', '/']
memory = 0


def solution():
    global x
    global y
    global operation
    while True:
        print(msg_0)
        calc = input()
        lst = calc.split(' ')
        operation = lst[1]
        x = lst[0]
        y = lst[2]
        if x == str('M'):
            x = memory
        elif y == str('M'):
            y = memory
        try:
            x = float(lst[0])
            y = float(lst[2])
        except ValueError:
            print(msg_1)
            continue
        try:
            if operation in oper:
                break
            else:
                print(msg_2)
        except ValueError:
            continue


def calculations():
    global res
    res = 0
    if operation == oper[0]:
        res = x + y
        return res
    elif operation == oper[1]:
        res = x - y
        return res
    elif operation == oper[2]:
        res = x * y
        return res
    elif operation == oper[3] and y != 0:
        res = x / y
        return res
    else:
        print(msg_3)
        solution()


def store_res():
    print(msg_4)
    answer = input()
    if answer == 'y':
        memory = res
        answer_on_msg_5()
        return memory
    elif answer != 'n':
        store_res()
    else:
        answer_on_msg_5()


def answer_on_msg_5():
    print(msg_5)
    answer_1 = input()
    if answer_1 == 'y':
        solution()
    elif answer_1 != 'n':
        answer_on_msg_5()
    else:
        print()


solution()
calculations()
print(calculations())
store_res()
or is the logical operator.