2014-02-19 44 views
-4

如何通過從用戶輸入中收集矩形的高度和寬度,計算區域並顯示結果,來編寫計算矩形區域的程序?你怎麼用一個長方體的體積來做呢?我的代碼到目前爲止:(我剛剛開始python)如何在python 3.3.4中編寫一個程序來計算矩形區域?

shape = input("> ") 

height = input("Please enter the height: ") 

width = input("please enter the width: ") 

area = [height*width] 

print ("The area is", 'area') 

但我收到無效的語法。

+1

嗨!什麼是確切的錯誤?例如,它是否給出了有關錯誤的可用建議? –

+0

「形狀」背後有什麼打算? – Nabla

回答

4

在Python 3.x中,input返回一個字符串。所以,heightwidth都是字符串。

area = [height*width] 

您在這裏乘以字符串並創建一個列表。你需要將它們轉換爲任意整數(與int功能)或浮點數(帶float功能),這樣

height = float(input("Please enter the height: ")) 
width = float(input("please enter the width: ")) 
... 
area = height*width 

然後,它能夠更好地單個字符串傳遞給print功能,這樣

print ("The area is {}".format(area)) 

或者你可以簡單地打印這樣

print ("The area is", area) 
+1

那麼'int'可能不是長度最好的類型=) – luk32

+0

擊敗我吧+1。 –

+0

爲什麼使用字符串格式更好?我真的看不到任何優勢。 – Narcolei

0
print ("The area is", area) 

,你不需要的區域存儲在一個列表 - area = height * width就夠了。

只要做到這一點類似於計算長方體的體積:

l = int(input("Please enter the length: ")) 
h = int(input("Please enter the height: ")) 
w = int(input("please enter the width: ")) 
vol = l*h*w 

print ("The volume is", vol) 

請注意,您需要在嘗試做任何數學與他們之前將用戶輸入轉換爲int

0

的項目確保用戶只能夠進入佛羅里達州燕麥和其他沒有琴絃,你會得到一個錯誤:

height = float(input("What is the height?") 

一旦你有了兩者的輸入,則輸出:

area = height * width 
print("The area is{0}".format(area)) 
相關問題