【问题标题】:How to draw a checkered flag to the Python screen?如何在 Python 屏幕上绘制方格旗?
【发布时间】:2015-04-08 03:42:27
【问题描述】:

问题:实现以下伪代码以在屏幕上绘制方格旗。

1.  Ask the user for the size of the checkered flag (n).
2.  Draw an n x n grid to the screen.
3.  For i = 0,2,4,...,62:
4.     row = i // n
5.     offset = row % 2
6.     col = (i % n) + offset

请复制并粘贴链接查看输出:http://www.awesomescreenshot.com/image/45977/12eaef67de44c2b291ecd47fe8d10135

我实现了伪代码,但我需要一些帮助。我不断收到此错误:row, col = findGrid(x) TypeError: 'int' object is not iterable

我的程序:

from turtle import*

def size():
  size = eval(input("Please enter the size of the checkered flag: "))
  return size

def draw(n):
  wn = Screen()
  wn.setworldcoordinates(-1,-1,10,10)
  pen = Turtle()
  for i in range(0,n+1):
    pen.up()
    pen.goto(0,i)
    pen.down()
    pen.forward(n)

  pen.left(90)
  for i in range(0,n+1):
    pen.up()
    pen.goto(i,0)
    pen.down()
    pen.forward(n)

def findGrid(n):
  for i in range(0,63):
    row = i // n
    offset = row % 2
    col = (i % n) + offset

  return row
  return col

def fillSquare(x,y):
  pen = Turtle()
  pen.hideturtle()
  pen.speed(10)
  pen.up()
  pen.goto(x,y)
  pen.fillcolor("black")
  pen.begin_fill()

def main():
  x = size()
  y = draw(x)
  row, col = findGrid(x)
  f = fillSquare(row, col)

main()

【问题讨论】:

    标签: python format turtle-graphics


    【解决方案1】:

    如果你想return 两个值,你必须以某种方式组合它们。如果你这样做:

    return row
    return col
    

    程序将 return row 然后退出函数,因为这就是 return 所做的。第一个 return 之后的任何内容都不会被执行。试试这个:

    return row, col
    

    返回的值将是tuple,这正是您执行row, col = findGrid(x) 所需的值,如您的main() 中所示。 findGrid(x) 不会评估为单个 int,而是评估为包含两个 ints 的 tuple,Python 可以遍历该 tuple 以将每个值放入指定的变量 row 和 @ 987654337@.

    Python 解释器生成的错误消息通常信息量很大。在这种情况下,当它显示 int object is not iterable 时,您可以打赌它试图迭代 int 并且可以理解地失败了。然后,您所要做的就是推断出有问题的错误语句在哪里寻找可迭代对象,找到产生问题表达式 (findGrid(x)) 的原因,并检查它是否返回 int 或可迭代对象。

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多