在Python中制作一个符合这些规格的空心盒子?

时间:2013-12-05 04:59:57

标签: python

我要“编写一个python程序,提示用户输入一个正整数n。程序然后打印一个有n行和2 * n列的空心矩形。例如,输入3将输出:”

******
*    *
******

我的代码是:

n=int(input('Please enter a positive integer between 1 and 15: '))
for col in range(n):
    for row in range(n):
        print('*' if col in(0,(2*n)+1) or row in(0,n+1) else ' ', end=' ')
    print()

但我的输出并不像我需要的那样;它就像一个空心盒子的上半部分和左半部分。另外,我没有得到像我需要的双列。我做错了什么?

编辑:谢谢大家的帮助!给了我很多洞察力,非常有帮助。我将我的代码修改为以下内容,并且效果非常好:

>n=int(input('Please enter a positive integer between 1 and 15: '))
>for row in range(n):
>    for col in range(2*n):
>        print('*' if row in(0,n-1) or col in(0,(2*n)-1) else ' ', end=' ')
>    print()

特别关注user2357112;你让我意识到我绊倒了什么。

5 个答案:

答案 0 :(得分:0)

代码应该是:

line =  "*"*(2*n)
print line
s  = "*" + " "*(n-2) + "*"
for i in range(n-2):
    print s
print line         

该行:

"*"*(2*n)

指定字符串“*”,重复2 * n次。你想要2 * n列右..这打印2 * n“*”

答案 1 :(得分:0)

<强>代码:

def printStars(length):
    l = ['*'*length]
    l+= ['*' + ' '*(length-2) + '*'] * (length-2)
    l+= ['*'*length]

    return l

if __name__=='__main__':
    print('\n'.join(printStars(15)))

输出

***************
*             *
*             *
*             *
*             *
*             *
*             *
*             *
*             *
*             *
*             *
*             *
*             *
*             *
***************

希望这会有所帮助:)

编辑:修正了一些格式

答案 2 :(得分:0)

def make_box():       
    size = int(input('Please enter a positive integer between 1 and 15: '))
    for i in range(size):
        if i == 0 or i == size - 1:
            print("*"*(size+2))
        else:
            print("*" + " "*size + "*")


make_box()

输出(n = 15)

*****************
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*               *
*****************

答案 3 :(得分:0)

我的解决方案:

# Response to StackOverflow post:
# Making a hollow box in Python

# The multiplication operator (*) is the same as repeated
# concatenation when applied to strings in Python.

# I solved the problem by creating an array with N elements
# and gluing them together (str.join(array)) with newline
# characters.

# I trust you're already familiar with string formatting and
# concatenation, but in case you're not, please feel free to
# ask for clarification.


def main():
    n = int (input("Enter an integer between 1 and 15"))
    box = "\n".join(["*"*(2*n)] + ["*%s*" % (" "*(2*n-2))]*(n-2) + ["*"*(int(n>1)*2*n)])
    print (box)


if __name__ == '__main__':
    main()
    input() # Prevents the console from closing immediately

至于你的解决方案。在我看来,循环条件搞砸了;列和行循环的顺序相反,列循环中range()的参数应为2 * n(因为这是每行相交的列数)。您还应该再次查看第一个打印语句中的条件。

答案 4 :(得分:0)

我的解决方案比较基础。请考虑一下:

row = abs(eval(input('Enter row: ')))
col = abs(eval(input('Enter column: ')))
print ('*'*col)

for i in range (row-2):
      print ('*'+' '*(col-2)+'*')
print ('*'*col)