How Can I Make The Program To Rerun Itself In Python?
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
Solution 1:
Loop over that code and break
when you want to stop repeating:
whileTrue: # 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
Solution 2:
We can do this by writing this in a function and make it as recursive function like below.
defcalculator():
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()
Solution 3:
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")
Post a Comment for "How Can I Make The Program To Rerun Itself In Python?"