我正在编写一个函数,根据用户的输入获取一个网格打印出来。到目前为止,我能够让它打印一个简单的版本,其中它改变了大小,例如:
print_grid(15)
#prints a larger grid:
+ - - - - - - - + - - - - - - - +
| | |
| | |
| | |
| | |
| | |
| | |
| | |
+ - - - - - - - + - - - - - - - +
| | |
| | |
| | |
| | |
| | |
| | |
| | |
+ - - - - - - - + - - - - - - - +但是现在我尝试做一些事情,这样它就可以接受两个输入变量(x,y),其中x是行/列(area)的数目,y是较大整体中单个、较小的网格的大小。例如,print_grid2(3,4)导致:
+ - - - - + - - - - + - - - - +
| | | |
| | | |
| | | |
| | | |
+ - - - - + - - - - + - - - - +
| | | |
| | | |
| | | |
| | | |
+ - - - - + - - - - + - - - - +
| | | |
| | | |
| | | |
| | | |
+ - - - - + - - - - + - - - - +我重用了第一个网格示例中的一些代码,然后对它进行了修改,以适应这个特定的任务,但是这次我没有得到任何输出,并且不确定如果我没有得到任何输出。任何帮助都是非常感谢的。(我还没有更新我的评论,所以我意识到它们已经不再有意义了,因为它们与上一次迭代有关)。
现行法典:
def grid_print(area, units):
print_Area = (area * area)
grid_rows = units + (units + 1) + 2
grid_cols = units + 2
if units % 2 == 0: # If grid entry is even (it will end up making
grid_rows += 1 # the square uneven, so increase number of rows by 1
# now grid is technically uneven
for i in range(print_Area):
for row in range(grid_rows): # for each item in number of items(rows)
for col in range(grid_cols): # for each item in number of items(columns)
if row == 0 or row == int(grid_rows/2) or row == grid_rows -1: # if item is beginning, middle or end
# -- Formatting beam structure -- #
if col == 0: # beginning, print '+' no '\n'
print('+', end='')
elif col == grid_cols -1: # end, print '+'
print('+')
elif int(grid_cols/2) == col: # middle:
if grid_rows % 2 == 0: # if grid is even, pad '+' with ' '
print(' + ', end='') # if grid is uneven, no padding
else: # print '+' no '\n'
print('+', end='')
elif col % 2 == 0: # if col item is an even number
print('-', end='') # print '-' with no '\n'
else: # else if col item is uneven item num
print(' ', end='') # print ' ' no '\n'
else:
# -- Formatting line structure -- #
if col == 0: # if column is at starting position 0
print('|', end='') # print '|' no '\n'
elif col == int(grid_cols/2): # if column is at middle pos
if units % 2 == 0: # print '|' no '\n'
print(' | ', end='') # (has padding if grid is even or not)
else:
print('|', end='')
elif col == grid_cols -1: # if column is at end position of grid
print("|") # print '|'
else:
print(' ', end='') # all other circumstances, print ' ' no '\n'发布于 2018-04-30 18:54:39
因此,在您的代码中,可能只是在if units % 2 == 0:之后出现缩进错误,但是可以将整个代码压缩到以下行:
def print_grid(area, unit):
for _ in range(area):
print(("+" + "- " * unit) * area + "+")
for _ in range(unit):
print(("|" + " " * unit) * area + "|")
print(("+" + "- " * unit) * area + "+")
print_grid(3, 4)指纹:
+--------+--------+--------+
| | | |
| | | |
| | | |
| | | |
+--------+--------+--------+
| | | |
| | | |
| | | |
| | | |
+--------+--------+--------+
| | | |
| | | |
| | | |
| | | |
+--------+--------+--------+https://stackoverflow.com/questions/50106387
复制相似问题