I've been trying to get this program to print a hollow square but I keep getting syntax errors, any help would be appreciated, thank you.
n=int(input('Please input an integer :')
cnt1 = 0
while (cnt1 < n)
print('*')
print('\n')
cnt1 = 0
while (cnt1 < (n-2)
print('*)
cnt2 = 0
while cnt2 < (n-2)
print (" ")
cnt2++
print("*\n")
cnt1++
cnt1 = 0
while(cnt1 < n)
print('*')
cnt1++
There are numerous problems with the code as you have pasted it, among them:
++
operator, you should use += 1
. :
following them.end=
. There may be others I forgot in the process of fixing the code but the following is probably more what you were after (assuming Python 3 due to your use of parentheses on the print
and use of input
rather than raw_input
):
n = int(input('Please input an integer : '))
cnt1 = 0
while cnt1 < n:
print('*',end='')
cnt1 += 1
print()
cnt1 = 0
while cnt1 < (n-2):
print('*',end='')
cnt2 = 0
while cnt2 < (n-2):
print (' ',end='')
cnt2 += 1
print('*')
cnt1 += 1
cnt1 = 0
while cnt1 < n:
print('*',end='')
cnt1 += 1
print('\n')
Of course, there's no actual need for all those counter-controlled loops, Python provides a rich set of features for keeping your code short and maintainable (and you should generally always check user input for problems):
try:
n = int(input('Please input an integer : '))
except:
print('Problem with input, using ten instead.')
n = 10
if n > 1:
edge = '*' * n
mid = '*%s*' % (' ' * (n-2))
print(edge)
for i in range(n-2): print(mid)
print(edge)
else:
print('Needs to be two or more')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.