编写一个接受三个输入的函数
create_box
:height
(行(、width
(列(和字符char
,并创建使用字符CCD_ 6的CCD_。
这是我的代码:
def create_box(height, width, char):
for i in range (height):
for j in range(width):
z = char * j + "n"
return z
这个代码的问题是它只返回一行输出。我想知道怎样才能退货?我们是否可以将return
语句放置为在完成first-for循环的所有迭代后返回?
我也试过这个:
def create_box(height, width, char):
z = ""
for i in range (height):
for j in range(width):
z += char * width + "n"
return z
ma = create_box(3, 5, "!")
print(ma)
输出为:
!!!!!
!!!!!
!!!!!
!!!!!
!!!!!
使用第二种方法,您几乎已经完成了正确的操作:这是工作代码。
def create_box(height, width, char):
z = ""
for i in range (height):
for j in range(width):
z += char # Width number of chars
z += 'n' # Next row
return z
ma = create_box(3, 5, "!")
print(ma)
您所做的只是弄乱了return语句的缩进,并错误地添加到字符串中。如果你不明白这里的逻辑,发表评论,我会充分解释。
输出:
>>> print(create_box(1, 1, '-'))
-
>>> print(create_box(3, 2, '* '))
* *
* *
* *
# Etc etc
回复您的评论:
你的第一个代码不起作用的原因是方法错误,看看这个:
z = 0
for i in range(5):
z += i
print(z)
# You expected this to output 5, it doesn't
第二次尝试在两个方面是错误的:
- 您的
return
语句缩进错误,导致函数在完成外循环的第一次迭代后停止执行。请参见以下内容:
def hello():
print("This gets printed")
return
print("This is never executed")
hello()
# Run it and see for yourself!
z
变量:z随机上升,循环所需的第二步就是在每次迭代中向z
添加一个char
还有什么需要澄清的吗?