所以我必须写下一个返回形状的函数

  • 本文关键字:返回 函数 下一个 python
  • 更新时间 :
  • 英文 :


我需要编写一个函数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)

最新更新