我有一个计算机科学作业,我需要写一个函数main()
,它调用一个函数drawChessboard()
来绘制一个8x8的棋盘,在那里用户可以确定棋盘的宽度和高度。我们正在学习函数和模块,我们需要使用多个具有多个函数的模块。这是我的第一个模块:
from chessboard import *
def main():
startX, startY = eval(input("Enter the starting coordinates (x, y): "))
width = input("Enter the width: ")
height = input("Enter the height: ")
spaceX = eval(width) / 8
spaceY = eval(height) / 8
def variables():
global startX, startY, width, height, spaceX, spaceY, xLocation, yLocation
if width == "" and height == "":
drawChessboard(startX, startY)
elif height == "":
drawChessboard(startX, startY, width=eval(width))
elif width == "":
drawChessboard(startX, startY, height=eval(height))
else:
drawChessboard(startX, startY, eval(width), eval(height))
main()
这是第二个模块,名为:棋盘.py在
^{pr2}$当第一个height
。
我不知道怎么解决这个问题。我试着把所有变量都设为全局变量,但结果还是一样。我在这个网站上查到了这个错误,但是我没有运气。我做错什么了吗?在
你在这个函数中使用了两次高度
该函数中不存在该变量。不要使用global。你用身高
^{pr2}$所以你需要在这里做同样的事情
所以当你调用drawAllRectangles时,确保你传入了这4个变量。在
另外,将所有导入移到文件的顶部。看看eval做了什么(https://www.programiz.com/python-programming/methods/built-in/eval)。你不需要在你的程序中的任何地方都需要全局数据或评估。在
我同意@anon(+1)关于全局变量和代码中的
eval()
的观点。下面是我对你的代码san全局变量的重新设计,你应该能够根据需要把它分成两个单独的文件。您需要(重新)阅读global
关键字的作用和使用位置。我知道eval()
在输入元组时很方便,但是您应该找到另一种方法。我将其他eval()
调用替换为int()
:用pythonthurtle绘制棋盘并不需要太多代码和精力。我建议您研究一下
stamp()
,这样既可以加快速度又可以简化它。在相关问题 更多 >
编程相关推荐