我需要编写一个函数print_rect(ch,宽度,高度(,以矩形的形式打印出字符ch。矩形应具有尺寸宽度 * 高度。例如:
print_rect("*", 7, 5(
*******
*******
*******
*******
*******
但问题是我无法使它成为我想要的任何参数。 例如,如果我写下 print('?', 7, 5(,它应该给我带有 ? 标记,但它总是给我一个矩形。 我写的公式是:
def print_rect(ch, width, height):
for ch in range(height):
print ( "ch" * width)
and my output is
chchchchch
chchchchch
chchchchch
chchchchch
chchchchch
chchchchch
chchchchch
希望我的要求很清楚,对不起,如果我在解释时犯了错误,英语不是我的第一语言。
您需要遍历宽度和高度,并在每次迭代中打印出字符:
def print_rect(ch, width, height):
for h in range(height):
for w in range(width):
print(ch,end='')
print()
演示:
print_rect('ch',5,6)
chchchchch
chchchchch
chchchchch
chchchchch
chchchchch
chchchchch
print_rect('*',3,2)
***
***
你也可以按照自己的方式做(这更优雅(:
def print_rect(ch, width, height):
for h in range(height):
print(ch*width)
但是你必须确保ch
是一个字符串。但是您可以将ch
转换为字符串:
def print_rect(ch, width, height):
for h in range(height):
print(str(ch)*width)
这里有 2 件主要的事情。 1.在打印行中,您要求打印字符串"ch"而不是参数
ch.2.在for循环中,您使用ch,但您已经将其用作字符。我改用了x。
def print_rect(ch, width, height):
for x in range(height):
print (ch* width)