2014-11-04 113 views
0

我試圖創建一個小片的代碼,使用畢達哥拉斯定理計算三角形的斜邊和高度相對的角的長度。爲此,用戶必須輸入三角形的長度和寬度。我想定義一個函數,以便可以將整個事件稱爲更大程序的一部分。下面的代碼:定義Python函數與用戶輸入

def ex1() : 
    from math import sqrt, atan, degrees 
    print("""Hello, this is a program that will calculate the length of the 
    hypotenuse of a triangle given the width and height of the triangle. 
    It will also calculate the angle opposite the height and adjacent to the width. 
    """) 

    myWidth = float(input("Please input the width of the triangle: ")) 
    myHeight = float(input("Please input the height of the triangle: ")) 
    hyp = sqrt(((myWidth**2) + (myHeight**2))) 
    angle = degrees(atan(myHeight/myWidth)) 
    print("\nThe length of the hypotenuse is " + "%.1f" % hyp + " units") 
    print("\nThe size of the angle opposite the height and \nadjacent to the width is " + "%.1f" % angle + " degrees to 1 decimal place") 
    input = input("Press enter to end the program\n") 

誰能給我解釋一下,當我叫它,它拋出,在我這個錯誤:

UnboundLocalError: local variable 'input' referenced before assignment 

提前非常感謝

+1

Python版本您使用的?如果它的'3.x'和上面只有那麼''輸入'work.Dont分配最後一行到一個變量(即第二個'input'語句。如果你還想要,使用一個不同的變量 – Beginner 2014-11-04 22:34:36

+0

它是,它是Python 3.3.2,所以我不能定義多個用戶輸入?好的,我會在程序結束時嘗試。 – 2014-11-04 22:36:35

+0

總是避免使用python關鍵字作爲變量名。input是一個關鍵字,它使得它是一個很大的不作爲'變量'的名稱選擇 – Beginner 2014-11-04 22:38:32

回答

2

這裏看到這一行:?

input = ... 

見幾行上面,你叫input()功能?你混淆了編譯器。使用不同的名稱。

1

這個問題似乎是你的最後一行,在那裏你將值分配給變量「輸入」。看到這個以前的SO問題:Local Variable Input