我想在python中做一个正方形,但我做错了

时间:2016-10-23 18:49:59

标签: python

我编写了这段代码:你输入方形宽度并创建一个,但是当创建方形时,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) + '|')

1 个答案:

答案 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.