2014-02-19 34 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)) 
相关问题