2014-01-24 51 views
1

我想更改循環,以便用戶可以輸入深度爲十進制。奇怪的是,當我用直整數運行它時,程序工作正常。但是,如果我嘗試輸入小數進入深度我收到此錯誤信息: 「UnboundLocalError:局部變量‘區域’分配之前引用的」循環將不允許浮動

在總結,我可以接受如何改變回路允許小費非整數?我看到了一些關於xrange的事情,但是讓我困惑。有人可以請解釋我如何得到一個參考錯誤取決於用戶的輸入?

感謝

width = float(input("In inches, what is the width: ")) 
length = float(float(input("In inches, what is the length: "))) 
depth = int(float(input("In inches, what is the depth: "))) 

for i in range(depth): 
    area = 6*(length*width) 
    volume = length * width * depth 

print ("The area is: ", area, "square inches") 
print ("The volume is: ", volume, "cubic inches") 
+9

爲什麼你有一個循環呢? – Mat

+2

如果深度爲6.2,循環應運行多少次? – nmichaels

+2

爲什麼你甚至使用'for'循環? – IanAuld

回答

2

如果您需要在小數深度,你可以直接寫

depth = float(input("In inches, what is the depth: ")) 

和擺脫for

2

UnboundLocalError是因爲depth爲零。由於循環的主體未運行,因此未分配面積和體積。它看起來並不像你需要一個循環,所以你可以在開始時用for擺脫這一行,並在接下來的兩個時間裏取消,你就會全部設置好。

xrange是用Python版本3之前如果你發現自己使用其中的一個,把一個xrange面前,你就會有你使用的語義。

+0

好點。這些天我在照片中使用了parens,他們面前的空間把我扔掉了。 – nmichaels

+0

其實,他們可能會使用python 2.但是,他們不應該使用'input'。所以沒關係。 – geoffspear

0

解決你的問題,你有你的循環使用它之前宣佈area的。

爲了解決你的代碼的更全面的問題,您應該刪除for循環徹底:

width = float(input("In inches, what is the width: ")) 
length = float(float(input("In inches, what is the length: "))) 
depth = int(float(input("In inches, what is the depth: "))) # why are you casting this variable as both an int and a float? 

area = 6*(length*width) 
volume = length * width * depth 

print ("The area is: ", area, "square inches") 
print ("The volume is: ", volume, "cubic inches") 

一個for循環的目的是遍歷一個可迭代(列表,字典等)和執行操作上迭代中的每個項目。或者它可以與range一起使用來執行一定的操作次數。如果您希望用戶輸入深度的上限,以便他們可以查看所有達到該數字的整數的區域/音量,則在執行for i in range(depth)的情況下會很有用。

例如,如果他們正在設計一個水族館,需要最小的體積,但可以超過一定的體積,您的功能將能夠幫助他們瞭解什麼樣的深度適合要求。然而,我想你想要的只是計算面積/體積一次,所以根本就不需要循環。

現在至於鑄造變量這是從內部讀出。所以你正在採取input這是一個string,把它作爲float(這是你想要的),然後將它作爲int將它放在最後的十進制值。爲了保持它作爲一個浮動:

depth = float(input(blah...))

是所有必需的。