制作一个正方形
我刚开始学习用Python编程,最近被分配了一个项目,要用蒙特卡罗算法来近似计算圆周率的值。我已经理解了这个概念,但现在需要打印出一个正方形,并在上面标记一些勾号。这个正方形的大小需要由用户设置。
我已经用以下代码成功打印出了正方形:
import random
#defines the size of the square
squareSize = raw_input("Enter a square size:")
#defines the width of the square
print "#" * (int(squareSize)+2)
#defines the length of the square.
for i in range(0,int(squareSize)):
print "#", " " * (int(squareSize)-2), "#"
print "#" * (int(squareSize)+2)
但是不管出于什么原因,当我添加:
#determines the x value of a point to display
x = random.uniform(-1*(squareSize),squareSize)
或者其他任何会影响“squareSize”这个变量的东西时,我就会收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
File "/lib/python2.7/random.py", line 357, in uniform
return a + (b-a) * self.random()
TypeError: unsupported operand type(s) for -: 'str' and 'str'
我非常希望能得到一些帮助,我相信这一定是我忽略了什么简单的东西,但我就是想不出来。
谢谢,
亚历克斯。
2 个回答
1
这个 raw_input
函数返回的是一个字符串(str
),而不是一个整数(int
)。
因为 squareSize
是一个字符串,所以你不能对它进行 -
这样的操作。
这是因为你其实想做的是减法(或者说 random
函数想要做的),而减法是需要两个整数来进行的。
所以,为了实现这个目的,你可以把 squareSize
变量的类型转换一下,把 raw_input
返回的字符串变成一个整数(int
)。
#defines the size of the square
squareSize = raw_input("Enter a square size:")
3
问题在于 squareSize
是一个 str
类型的字符串。而 random.uniform 这个函数需要的是 int
类型的数字。
你可以通过简单的方式来解决这个问题:
x = random.uniform(-1*(int(squareSize)),int(squareSize))
不过,最好是在一开始就把 squareSize
转换成 int
类型:
squareSize = int(raw_input("Enter a square size:"))
最终代码应该看起来像这样:
import random
squareSize = int(raw_input("Enter a square size:"))
print "#" * (squareSize + 2)
for i in range(0,squareSize):
print "#", " " * (squareSize) - 2, "#"
print "#" * (squareSize + 2)
x = random.uniform(-1 * squareSize, squareSize)
希望这能帮到你。