2017-01-14 4 views
1

Всякий раз, когда я печатаю «no» для «Хотели бы вы найти область другой формы?» он снова задает мне вопрос. Вот мой код: -Почему мой код python работает дважды?

def calculate_area(): 
    print "Welcome to the area calculator" 
    user= raw_input("Enter the shape you would like to calculate the area of:").lower() 

    def restart(): 
    answer= raw_input("Would you like to find the area of another shape?('yes' or 'no')") 
    if answer=="yes": 
     calculate_area() 
    def rerun(): 
    restart() 


    if user== "rectangle": 
    def calculate_rectangle(): 
     rect1= int(raw_input("Enter the length of the first side:")) 
     rect2= int(raw_input("Enter the length of the second side:")) 
     print "The area is:",float(rect1*rect2) 
    calculate_rectangle() 
    rerun() 

    elif user== "square": 
    def calculate_square(): 
     square=int(raw_input("Enter the length of the side:")) 
     print "The area is:",float(square**2) 
    calculate_square() 
    rerun() 


    elif user== "triangle": 
    def calculate_triangle(): 
     triangle=int(raw_input("Enter the length of the base:")) 
     triangle2=int(raw_input("Enter the height of the triangle:")) 
     print "The area is:", float((0.5*triangle)*triangle2) 
    calculate_triangle() 
    rerun() 


    elif user== "trapezoid": 
    def calculate_trap(): 
     trapezoid=int(raw_input("Enter the length of base 1:")) 
     trapezoid2=int(raw_input("Enter the length of base 2:")) 
     trapezoid3=int(raw_input("Enter the height:")) 
     print "The area is:", (float(trapezoid+trapezoid2)/2*float(trapezoid3)) 
    calculate_trap() 
    rerun() 

    elif user== "circle": 
    def calculate_circle(): 
     circle=int(raw_input("Enter the radius:")) 
     print "The area is:", (float((circle**2)*3.14)) 
    calculate_circle() 
    rerun() 

    elif user== "rhombus": 
    def calculate_rhombus(): 
     rhombus1=int(raw_input("Enter the length of diagonal 1:")) 
     rhombus2=int(raw_input("Enter the length of diagonal 2:")) 
     print "The area is:", (float((rhombus1*rhombus2)/2)) 
    calculate_rhombus() 
    rerun()  

    else: 
    print "Shape not recognized" 
    rerun() 

Этот код находится под «def restart» и выполняется дважды, когда я набираю «no». Почему это происходит?

+4

, потому что есть 'Перекладка()' в конце функции ... – mguijarr

+0

Вы пробовали запустить его под отладчиком, с точкой останова на линии «Хотите ли вы найти область другой формы»? Проверьте трассировки стека в обоих случаях, и я думаю, вы узнаете ответ. – alf

+0

Ваш последний '' 'rerun()' '' не имеет отступ под финальным блоком '' 'else'''. –

ответ

0

Последнее Перекладка() должен быть в заявлении еще:

print ("Welcome to the area calculator") 
    user = raw_input("Enter the shape you would like to calculate the area of:").lower() 

    def restart(): 
    answer = raw_input("Would you like to find the area of another shape?('yes' or 'no')") 
    if answer == "yes": 
     calculate_area() 
    def rerun(): 
    restart() 


    if user == "rectangle": 
    def calculate_rectangle(): 
     rect1 = int(raw_input("Enter the length of the first side:")) 
     rect2 = int(raw_input("Enter the length of the second side:")) 
     print "The area is: ",float(rect1 * rect2) 
    calculate_rectangle() 
    rerun() 

    elif user == "square": 
    def calculate_square(): 
     square=int(raw_input("Enter the length of the side:")) 
     print "The area is: ",float(square ** 2) 
    calculate_square() 
    rerun() 


    elif user == "triangle": 
    def calculate_triangle(): 
     triangle = int(raw_input("Enter the length of the base:")) 
     triangle2 = int(raw_input("Enter the height of the triangle:")) 
     print "The area is: ", float((0.5 * triangle) * triangle2) 
    calculate_triangle() 
    rerun() 


    elif user == "trapezoid": 
    def calculate_trap(): 
     trapezoid = int(raw_input("Enter the length of base 1:")) 
     trapezoid2 = int(raw_input("Enter the length of base 2:")) 
     trapezoid3 = int(raw_input("Enter the height:")) 
     print "The area is: ", (float(trapezoid + trapezoid2)/2 * float(trapezoid3)) 
    calculate_trap() 
    rerun() 

    elif user == "circle": 
    def calculate_circle(): 
     circle = int(raw_input("Enter the radius:")) 
     print "The area is: ", (float((circle ** 2)*3.14)) 
    calculate_circle() 
    rerun() 

    elif user == "rhombus": 
    def calculate_rhombus(): 
     rhombus1 = int(raw_input("Enter the length of diagonal 1:")) 
     rhombus2 = int(raw_input("Enter the length of diagonal 2:")) 
     print "The area is: ", (float((rhombus1 * rhombus2)/2)) 
    calculate_rhombus() 
    rerun()  

    else: 
    print "Shape not recognized" 
    rerun() 
+0

Спасибо! Я этого не видел. Полагая внутри другого, работал. –

1

У вас есть rerun() в конце вашего метода.

Отрывок:

...removed... 
    else: 
    print "Shape not recognized" 
    rerun() 
3

Вы называете rerun() дважды для каждого вопроса:

if user== "rectangle": 
    # ... 
    rerun() 

elif user== "square": 
    # ... 
    rerun() 

# all other elif branches each have rerun() 

else: 
    print "Shape not recognized" 
rerun() 

Вы полагаетесь на рекурсии здесь, но рекурсивные функции возврата; когда вы вводите "No", restart() возвращается к rerun(), который возвращает управление к точке, где он был вызван, поэтому в одном из ваших if ... elif ... веток. И после те ветки, которые вы называете rerun() еще раз.

Вы не должны использовать рекурсию в первую очередь. Используйте бесконечный цикл вместо того, чтобы:

print "Welcome to the area calculator" 

while True: 
    user = raw_input("Enter the shape you would like to calculate the area of:").lower() 
    # execute their choice 
    if user== "rectangle": 
     # ... 
    # etc. 

    else: 
     print "Shape not recognized" 

    answer = raw_input("Would you like to find the area of another shape?('yes' or 'no')") 
    if answer != "yes": 
     break 

break в конце заканчивает цикл while True. Если введено значение yes, цикл while продолжается сверху, снова запустив весь блок.

Смежные вопросы