Why does it repeat from the top of the if rather than the while statement? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why does it repeat from the top of the if rather than the while statement?

I want to make the "repeat = input("Do you want to perform another calcualtion?(Y/N)") " return to the top of the while function so that it'll ask what kind of operation it'd like to do! Also, besides dictionaries and the 'not in' function, how else can i make this code neater and make "repeat = input("Do you want to perform another calcualtion?(Y/N)") " asked after every if or elif or else statement without manually placing it... THANK YOU! Here's my code... """try to make it repeat!""" repeat = "y" """Import functions here""" from math import pi """Calculator""" #Definitions def add(x,y): return x+y def sub(x,y): return x-y def div(x,y): return x/y def mul(x,y): return x*y def square(x): return x**2 def SquareRoot(x): return x**(1/2) #Code choice = input("Input type of operation!(+,-,*,/,^2,^1/2)") while repeat == "y": if choice == "+" or choice == "plus" or choice == "add" or choice == "-" or choice == "Subtract" or choice =="sub" or choice =="minus" or choice == "/" or choice == "divide" or choice == "division" or choice=="Multiply" or choice == "*" or choice == "times" or choice == "Multiplication": num1 = int(input("ENTER FIRST NUMBER")) num2 = int(input("ENTER SECOND NUMBER")) if choice == "+" or choice == "plus" or choice == "add": print(num1,"+",num2,"=",(num1+num2)) repeat = input("Do you want to perform another calcualtion?(Y/N)") elif choice == "-" or choice == "Subtract" or choice =="sub" or choice =="minus": print(num1,"-",num2,"=",(num1-num2)) repeat = input("Do you want to perform another calcualtion?(Y/N)") elif choice == "/" or choice == "divide" or choice == "division": print(num1,"/",num2,"=",(num1/num2)) repeat = input("Do you want to perform another calcualtion?(Y/N)") elif choice == "Multiply" or choice == "*" or choice == "times" or choice == "Multiplication":

14th Nov 2016, 11:02 PM
Dave Matthew
Dave Matthew - avatar
2 Answers
+ 2
1. To fix your bug, move the line 'choice =...' below your 'while...' statement, (indented by 2, like your 'if' statement, ofcourse). 2. You are violating the DRY principle by duplicating the 'repeat =...' statement after every 'if'. take it out, and place it once at the end of your code, with the same indentation if the original 'if'. this way after all 'if' branches are done, this statement will be executed next, before the end of the 'while' loop.
15th Nov 2016, 6:14 AM
Udi Finkelstein
Udi Finkelstein - avatar
0
THANKS
15th Nov 2016, 6:28 AM
Dave Matthew
Dave Matthew - avatar