I am trying to write a python program that does addition, subtraction, division, and multiplication. When it completes an equation, it needs to ask the user if they want it to repeat the program to do another equation. I have already written the calculator, but how do I make it able to repeat at the user's request?
Would it work to make the calculator a function that could be called? How would I set that up to be able to repeat? I'm just starting out with python so any guidance on how to format this would be great. Thanks in advance!
Here is my calculator if that helps
amount= int(input("how many numbers will you be calculating?"))
list=[]
count=0
while count<amount:
s=int(input("enter a number:"))
list.append(s)
count= count 1
print("your numbers are: ",list)
choice= input("enter a choice exactly as written in this list: add, subtract, multiply, or divide: ")
if choice== "add" :
print("you chose addition")
sum=0
for i in list:
sum=sum i
print("the sum of your numbers is: ", sum)
if choice== "subtract" :
print("you chose subtraction")
sum=list[0] list [0]
for i in list:
sum= sum-i
print("the difference between your numbers is: ",sum)
if choice== "multiply":
print("you chose multiplication")
sum=1
for i in list:
sum=sum*i
print(sum)
if choice== "divide":
print("you chose division")
sum=list[0]*list[0]
for i in list:
sum=sum/i
print(sum)
CodePudding user response:
You could wrap it in a while True:
loop and break out of it at the end of the code. For example:
while True:
# Code here
if input("Do you want to calculate something else (y/n)? ") != "y":
break
CodePudding user response:
one simple way to do it is just as you said, make the calculator a function and then you can do something like this
while True:
print("Continue")
n = str(input())
if n == "Yes":
calculator() #funtion call for calculator
elif n == "No":
break
else:
print("Yes/No")
This is how I would do it, to make the code easier to understand but if you want you could just put the whole calculator on a loop or something else
CodePudding user response:
The answer to do this is to ask if the player would like to repeat:
while True:
start_again = input("Would you like to calculate another thing? (y/n)")
if start_again == "y" or "yes":
use_calculator() #function that uses the calculator again
if start_again == "n" or "no":
exit() #closes program
break