I am a beginner in programming right now and i know very less basic. I tried to create a calculator in python and it worked but i cant get it to rerun itself
i have tried things on some site but everything was way too complex for me to understand.
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again == 'Y':
//i want the program to rerun itself here
else:
print("OK!!")
If the user inputs Y i want the calculator to start again. Detailed answers would be appreciated. Thank You
Loop over that code and break
when you want to stop repeating:
while True: # Will start repeating here
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again != 'Y':
print("OK!! Exiting")
break # break to leave the loop
# It will loop automatically back to the top otherwise
We can do this by writing this in a function and make it as recursive function like below.
def calculator():
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again == 'Y':
calculator()
else:
print("OK!!")
calculator()
You can use a while loop
that will run the code again until the input is different from Y
:
go_again = 'Y'
while go_again == 'Y':
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again == 'Y':
print("while loop will run again")
else:
print("program will exit")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.