I\'m to \"Write a python program that prompts the user to input a positive integer n. The program then prints a hollow rectangle with n rows and 2*n columns. For a example an in
Code:
def printStars(length):
l = ['*'*length]
l+= ['*' + ' '*(length-2) + '*'] * (length-2)
l+= ['*'*length]
return l
if __name__=='__main__':
print('\n'.join(printStars(15)))
Output:
***************
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***************
Hope this helps :)
EDIT:Fixed Some Formatting
The code should be like:
line = "*"*(2*n)
print line
s = "*" + " "*(n-2) + "*"
for i in range(n-2):
print s
print line
The line:
"*"*(2*n)
specifies a string of "*", repeated 2*n times. You wanted 2*n column right.. This prints 2*n "*"
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()
Output: (n=15)
*****************
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*****************
My solution is more elementary. Please consider it :
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)
My solution:
# 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
As for your solution. it seems to me like the loop conditions are messed up; the column and row loops are in reverse order and the argument to range() in the column loop should be 2*n (since that's the number of columns intersecting each row). You should also take a second look at the conditions in the first print statement.