繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM