我的正方形/矩形面积计算代码有什么问题?

时间:2018-10-20 07:39:34

标签: python

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 or Rectangle?”。我输入Square,然后要求输入宽度,然后突然关闭。当我放入矩形时,也会发生同样的情况。再次,我是python的noobie,只是离开了我能找到的东西。我不确定如何为这个问题构图以寻找答案,所以我求助于此。

2 个答案:

答案 0 :(得分:0)

这可以工作:

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 :(得分:-1)

您的代码有几个问题。

1)条件

if input in shape:

您从未定义变量“输入”。此外,我不确定自己为什么要在这里检查条件。如果您要验证形状是矩形还是正方形,请考虑以下代码:

if shape in ["rectangle", "square"]:

2)代码

"Square, square"

什么都不做,实际上是无效的语法。

3)行

print(“给定正方形的面积为” +面积)

对于打印功能是无效的字符串连接。 (请注意,您可以通过这种方式在打印功能之外进行连接) 改用逗号。

print("The area of the given square is", area)
相关问题