It only gives the prompt after the first time the function is run. Once you have said yes to the prompt and run another operation, the prompt is no longer shown to rerun the function yet again. I want the "run another operation" prompt to be shown each time that the code is rerun, and for it to work, obviously. How can I do this?
print("WELCOME TO A TEXT INPUT BASED CALCULATOR, WRITTEN IN PYTHON!\nREMEMBER, ONLY INPUT YOUR NUMBER, WITHOUT ANY EXTRA CHARACTERS, TO AVOID ERRORS!\nTHANK YOU FOR USING OUR CALCULATOR!\n\n\n")
def calculator():
print("Select the operation you would like to perform:")
print("1. ADDITION\n2. SUBTRACTION\n3. MULTIPLICATION\n4. DIVISION\n")
operation = input()
if operation == "1":
num1 = input("\nEnter first number:\n")
num2 = input("\nEnter second number:\n")
print("Answer: " + str(int(float(num1) + float(num2))))
elif operation == "2":
num1 = input("\nEnter first number:\n")
num2 = input("\nEnter second number:\n")
print("Answer: " +str(int(float(num1) - float(num2))))
elif operation == "3":
num1 = input("\nEnter first number:\n")
num2 = input("\nEnter second number:\n")
print("Answer: " +str(int(float(num1) * float(num2))))
elif operation == "4":
num1 = input("\nEnter first number:\n")
num2 = input("\nEnter second number:\n")
print("Answer: " +str(int(float(num1) / float(num2))))
else:
print("Whoops... Invalid input.")
calculator()
print("\n");
rerunchoice = input ("Run another operation? (y/n) ");
print("\n")
if rerunchoice.lower() == "y":
calculator()
else:
print ("Thank you for using our calculator :)");
quit()
Okay, well lets look at what's going on. You define the calculator function, then call it.
So it runs once.
Then you have the
rerunchoicelogic, if the user enters 'y', you call it again.When it's finished running the second time, the program resumes where it left off - in your
ifcondition.Since it's done everything it needed to do in the if block, it exits the if block and hits your 'quit()' command. It's just doing what you told it to.
If you want it to run endlessly until the user opts out (by entering something besides 'y') you need a loop. A traditional programming class would tell you, in this situation, a
do/whileloop is best. Python doesn't really provide ado/while, but a simplewhileis fine.A
whileloop needs a sentinel variable to tell it when to exit. Set that to true, then run your loop. In this case, your loop consists ofwhilecondition to exit (note: you already set this to true, so it will run the first time)A more 'pythony' way (or at least more recursive) would be to move the exact same
rerunchoicelogic you inside the calculator() function. Then all you have to do is call the function and let it go.