print "This is to find the area of a rectangle "
print "What is the length of your rectangle?"
x = raw_input("The length of the rectangle is ")
print "What is the width of your rectangle?"
y= raw_input("The width of the rectangle is ")
z = x * y
print z
答案 0 :(得分:1)
raw_input()返回一个字符串。 Python不知道如何将字符串相乘并抛出TypeError
:
>>> x = raw_input("The length of the rectangle is ")
The length of the rectangle is 10
>>> type(x)
<type 'str'>
>>> y= raw_input("The width of the rectangle is ")
The width of the rectangle is 20
>>> type(y)
<type 'str'>
>>> x * y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
您需要将输入转换为int
:
x = int(raw_input("The length of the rectangle is "))
演示:
>>> x = int(raw_input("The length of the rectangle is "))
The length of the rectangle is 10
>>> y= int(raw_input("The width of the rectangle is "))
The width of the rectangle is 20
>>> z = x * y
>>> print z
200
答案 1 :(得分:1)
很简单,你不能乘以字符串。这是因为即使您输入数字,raw_input
也将所有输入存储为字符串。只需将其转换为int
即可解决问题:
print "This is to find the area of a rectangle "
print "What is the length of your rectangle?"
x = int(raw_input("The length of the rectangle is "))
print "What is the width of your rectangle?"
y= int(raw_input("The width of the rectangle is "))
z = x * y
print z
>>> a = raw_input('Enter value: ')
Enter value: 5
>>> type(a)
<type 'str'>
>>> b = int(raw_input('Enter value: '))
Enter value: 5
>>> type(b)
<type 'int'>
您还可以通过以下方式减少打印量:(它还使您的代码更易于理解)
x = int(raw_input("What is the length of your rectangle?: "))
y= int(raw_input("What is the width of your rectangle?: "))
z = x * y
print z