2015-11-06 2 views
0

Это простая программа python для вычисления области треугольника, которая не работает во всех тестовых случаях. Я сомневаюсь, что первый блоксоздает проблему, но я не уверен в этом. Может быть значение для ch не уточняется, так что это может создать больше проблем.Во время обработки вышеуказанного исключения произошло другое исключение: программа Python

Полный код: -

# area of traingle 
import cmath 
import sys 

def areaOfTriangle(z): 
    flag = 0 
    a, b, c, angle, area = 0, 0, 0, 0, 0 
    print(" What information about the tiangle you have? ") 
    print(" 1. Height and Base : ") 
    print(" 2. Length of three sides of triange : ") 
    print(" 3. Length of two sides and angle between them : ") 
    print(" 4. EXIT : \n") 
    try: 
     if flag == 0 and z == 2: 
      ch = int(input("Enter your choice : ")) 
    except: 
     print("OOPS..!! something went wrong, try again") 
     areaOfTriangle(2) 
    if ch == 1: 
     try: 
      a = float(input(" Enter height and base : ")) 
      b = float(input()) 
     except: 
      print("OOPS..!! something went wrong, try again") 
      flag = 1 
      areaOfTriangle(1) 
     area = (a*b)/2 
    elif ch == 2: 
     try: 
      a = float(input(" Enter length of three sides : ")) 
      b = float(input()) 
      c = float(input()) 
     except: 
      print("OOPS..!! Something went wrong, try again") 
      flag = 1 
      areaOfTriangle(1) 
     s = (a+b+c)/2 
     area = cmath.sqrt((s) * (s-a) * (s-b) * (s-c)) 
     area = abs(area) 
    elif ch == 3: 
     try: 
      a = float(input("Enter the base length : ")) 
      b = float(input("Enter the side length : ")) 
      angle = float(input("Enter the angle between the two sides : ")) 
     except: 
      print("OOPS..!! Something went wrong, try again") 
      flag = 1 
      areaOfTriangle(1) 
     area = (1/2) * a * b * cmath.sin(angle) 
     area = abs(area) 
    elif ch == 4: 
     sys.exit(0) 
    else: 
     print("wrong choice") 
    print("The area of the triangle is ", area) 
    return 
areaOfTriangle(2) 

Примечание: Я передаю z в функции areaOfTriangle(Z) только потому, что я не хочу, чтобы пользователь ввел выбор снова и снова, если любое исключение происходит после ввода выбор один раз.

Ошибка, которая тестирование для различных случае: -

[email protected]:~$ python3.5 ~/python/basic\ programs/2-area-triange.py 
What information about the tiangle you have? 
1. Height and Base : 
2. Length of three sides of triange : 
3. Length of two sides and angle between them : 
4. EXIT : 

Enter your choice : 1 
Enter height and base : 
OOPS..!! something went wrong, try again 
What information about the tiangle you have? 
1. Height and Base : 
2. Length of three sides of triange : 
3. Length of two sides and angle between them : 
4. EXIT : 

Traceback (most recent call last): 
    File "/home/amitwebhero/python/basic programs/2-area-triange.py", line 22, in areaOfTriangle 
    a = float(input(" Enter height and base : ")) 
ValueError: could not convert string to float: 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "/home/amitwebhero/python/basic programs/2-area-triange.py", line 58, in <module> 
    areaOfTriangle(2) 
    File "/home/amitwebhero/python/basic programs/2-area-triange.py", line 27, in areaOfTriangle 
    areaOfTriangle(1) 
    File "/home/amitwebhero/python/basic programs/2-area-triange.py", line 20, in areaOfTriangle 
    if ch == 1: 
UnboundLocalError: local variable 'ch' referenced before assignment 

Вот на этой линии Enter height and base : я нажал Enter ключа, который создал эту ошибку.

+1

Ваше назначение 'ch' находится в блоке if, что означает, что если' flag == 0 и z == 2: 'возвращает false,' ch' никогда не назначается –

+0

Это назначается в первый раз, когда i вызовите функцию, передав 2 в качестве аргумента, и в остальное время я не хочу изменять значение ch, поэтому я сохраняю z как 1 –

+1

Вы рекурсивно называете свою функцию. Каждый вызов в стеке имеет свой собственный набор локальных переменных. Нет «первого раза», потому что у вас нет цикла, который выполнял бы что-нибудь более одного раза. – dsh

ответ

2

Конечная ошибка является решение вашей проблемы: -

UnboundLocalError: local variable 'ch' referenced before assignment

Это означает, что переменная ч не присваивается любое значение, и доступ к нему осуществляется, который создает проблему.

В строке 27 of the code, ваш вызывает areaOfTriangle(1) и это рекурсия присваивает значение z = 1 и это не позволяет вашой ч быть назначена, так как ваши, если условие возвращает значение False.

Вы считаете, что значение ch, присвоенное при первом вызове, останется таким же в другой рекурсии, но это не так, как вы думали.

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