[英]What is wrong with my code on calculating area of square/rectangle?
shape = input("Square or Rectangle ? : ")
width = float(input("Enter The Width : "))
if input in shape :
"Square, square"
area = width * width
print ("")
print ("The Area Of The Given Square is" + area)
length = float(input("Enter The Area : "))
area = width * length
print ("")
print ("The Area Of The given Rectangle is ", area)
input("Enter To Exit")
我是 Python 腳本的新手,想制作一個簡單的 py 來計算正方形或矩形的面積。 但是當我打開它時,它要求輸入“方形還是矩形?” 我輸入 Square,然后它要求寬度並突然關閉。 當我放入矩形時也會發生同樣的情況。 再次,我是 python 的菜鳥,只是我能找到的東西。 我不確定如何為此提出一個問題來搜索並找到答案,所以我求助於提出一個問題。
這可以工作:
shape = raw_input("Square or Rectangle : ")
if shape == 'Square':
width = float(raw_input("Enter The Width : "))
area = width * width
print ("")
print ("The Area Of The Given Square is " + str(area))
if shape == 'Rectangle':
width = float(raw_input("Enter The Width : "))
length = float(raw_input("Enter The length : "))
area = width * length
print ("")
print ("The Area Of The given Rectangle is " + str(area))
休息你可以相應地提高。
您的代碼有幾個問題。
1) 條件
if input in shape:
您從未定義過變量“輸入”。 此外,我不確定您為什么要在這里檢查條件。 如果您嘗試驗證形狀是矩形還是正方形,請考慮使用以下代碼:
if shape in ["rectangle", "square"]:
2)代碼
"Square, square"
什么都不做,實際上是無效的語法。
3)線路
print("給定正方形的面積是" + area)
是打印函數的無效字符串連接。 (請注意,您可以在打印功能之外以這種方式連接)改用逗號。
print("The area of the given square is", area)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.