我编写了这段代码:你输入方形宽度并创建一个,但是当创建方形时,None
也会出现。为什么呢?
def square(width):
if width>=4 and width% 2 ==0:
inferior_superior(width)
for i in range(2):
side(width)
inferior_superior(width)
def inferior_superior(width):
print("+" + "-"*(width-2) + "+")
def side(width):
print('|' + ' '*(width-2) + '|')
答案 0 :(得分:3)
观察一下,在python提示符下,square
工作正常:
>>> square(6)
+----+
| |
| |
+----+
但是,如果您打印square
的结果,则会看到无:
>>> print(square(6))
+----+
| |
| |
+----+
None
解决方案是单独使用square(n)
,而不是print(square(n))
。
如果您愿意,可以将返回值指定给square
:
>>> def square(width):
... if width>=4 and width% 2 ==0:
... inferior_superior(width)
... for i in range(2):
... side(width)
... inferior_superior(width)
... return "Everything works A-OK."
...
现在,观察:
>>> print(square(6))
+----+
| |
| |
+----+
Everything works A-OK.