I'm working on my first calculator in python, and I need a method of storing the input of the inner function so that when I run the outer function again, it will check the result to see if it's already been run.
power_on = True
def calculator():
num_1 = float(input("What is the first number?\n"))
operation = input("What is the operation?\n")
num_2 = float(input("What is the second number?\n"))
if result != None:
num_1 = int(result)
operation = input("What is the operation? \n , -, *, / \n")
num_2 = float(input("What is the second number?"))
def calculate():
if operation == " ":
return num_1 num_2
elif operation == "-":
return num_1 - num_2
elif operation == "*":
return num_1 * num_2
elif operation == "/":
return num_1 / num_2
else:
return "Invalid operation"
result = calculate()
print(f"{num_1} {operation} {num_2} = {result}")
usercont = input(f"Would you like to continue operating with {result}? \nEnter Y to continue, enter N to restart\n")
if usercont == "N":
result = None
while power_on == True:
calculator()
As you can see, this will generate an unbound local error because we're checking whether result
has a value or not before we get a value from the inner function. The issue is that I have no way to correct this error without overwriting whatever the result actually is... if I assign result = ""
under def calculator()
then I solve the error but never retain my value.
I know this is a noob question but I would appreciate any help for figuring this out.
Thank you.
CodePudding user response:
If you declare the result
variable outside of a loop and initialize it to None
, you can reference that when choosing to ask about num_1
or not.
like this:
power_on = True
def calculate(operation, num_1, num_2):
if operation == " ":
return num_1 num_2
elif operation == "-":
return num_1 - num_2
elif operation == "*":
return num_1 * num_2
elif operation == "/":
return num_1 / num_2
else:
return "Invalid operation, dicklicker"
def calculator(power_on):
result = None # starts off with no result
while power_on:
if result is None:
num_1 = float(input("What is the first number?\n"))
else:
num_1 = int(result)
operation = input("What is the operation?\n")
num_2 = float(input("What is the second number?\n"))
result = calculate(operation, num_1, num_2)
print(f"{num_1} {operation} {num_2} = {result}")
usercont = input(f"Would you like to continue operating with {result}?"
" \nEnter Y to continue, enter N to restart\n")
if usercont == "N":
result = None
calculator(power_on)
I cleaned up a little bit to make it more readable also.