编写一个程序,在屏幕上显示数字网格和每行的总数
以下程序显示数字网格和总数 每一行。填写此程序缺少的函数定义。 也就是说,编写函数
sumRow():
和display():
wn = Screen() #The graphics window nums = [[4,3,2,1], #The numbers to be displayed to the screen [8,7,6,5], [12,11,10,9], [16,15,14,13], [20,19,18,17]] n = len(nums) #The number of rows m = len(nums[0]) #The number of columns (assumes all same length) wn.setworldcoordinates(-0.5,n-0.5,m+2,-1.0) for row in range(n): rowTotal = sumRow(nums[row]) #Returns the sum of inputted list for col in range(m): display(nums[row][col], col, row) #Displays entry at (col,row) display("=", col+1, row) #Displays "=" at (col+1,row) display(rowTotal, col+2, row) #Displays row total at (col+2,row) wn.exitonclick() #Closes the graphics window when mouse is clicked
所以我把这个函数添加到上面的程序中。我还是很困惑。请帮忙!
from turtle import*
def sumRow(nums):
row = sum(nums[0])+ sum(num[1]) + sum(num[2]) + sum(num[3]) + sum(num[4])
return row
def display(num, col, row)
pen = Turtle()
pen.up()
pen.goto(col,row)
pen.down()
pen.write(nums[row][co1])
答案 0 :(得分:2)
sum()
获取值的序列。您将为其提供单个值,这将产生异常:
>>> sum(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
那是因为个别整数不能被迭代;迭代是循环,依次获取每个值。
只需将整行传递给sum()
,然后返回函数的结果:
def sumRow(nums):
total = sum(nums)
return total
您可以将其简化为:
def sumRow(nums):
return sum(nums)
甚至只是这样做:
sumRow = sum
并且它们都完全相同,生成传递给函数的列表nums
中所有值的总和。
您的显示功能被传递实际值以写为num
,您不必使用nums
上的索引来访问该号码:
def display(num, col, row):
pen = Turtle()
pen.up()
pen.goto(col,row)
pen.down()
pen.write(num)
这样,该函数也可以写=
字符和行的总数!