I have written a python program for printing a diamond. It is working properly except that it is printing an extra kite after printing a diamond. May someone please help me to remove this bug? I can't find it and please give a fix from this code please. CODE:
limitRows = int(input("Enter the maximum number of rows: "))
maxRows = limitRows (limitRows - 1)
while currentRow <= limitRows:
spaces = limitRows - currentRow
while spaces > 0:
print(" ", end='')
spaces -= 1
stars = currentRow
while stars > 0:
print("*", end=' ')
stars -= 1
print()
currentRow = 1
while currentRow <= maxRows:
leftRows = maxRows - currentRow 1
while leftRows > 0:
spaces = limitRows - leftRows
while spaces > 0:
print(" ", end='')
spaces -= 1
stars = leftRows
while stars > 0:
print("*", end=' ')
stars -= 1
print()
leftRows -= 1
currentRow = 1
OUTPUT(Case 1):
D:\Python\diamond\venv\Scripts\python.exe D:/Python/diamond/main.py
Enter the maximum number of rows: 4
*
* *
* * *
* * * *
* * *
* *
*
* *
*
*
Process finished with exit code 0
OUTPUT(Case 2):
D:\Python\diamond\venv\Scripts\python.exe D:/Python/diamond/main.py
Enter the maximum number of rows: 5
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
* * *
* *
*
* *
*
*
Process finished with exit code 0
CodePudding user response:
You have an extra while loop in the second half of your code.
Try this
limitRows = int(input("Enter the maximum number of rows: "))
maxRows = limitRows (limitRows - 1)
currentRow = 0
while currentRow <= limitRows:
spaces = limitRows - currentRow
while spaces > 0:
print(" ", end='')
spaces -= 1
stars = currentRow
while stars > 0:
print("*", end=' ')
stars -= 1
print()
currentRow = 1
while currentRow <= maxRows:
leftRows = maxRows - currentRow 1
spaces = limitRows - leftRows # Removed unnecessary while loop here
while spaces > 0:
print(" ", end='')
spaces -= 1
stars = leftRows
while stars > 0:
print("*", end=' ')
stars -= 1
print()
leftRows -= 1
currentRow = 1
CodePudding user response:
You can make this less complex by using just one loop as follows:
def make_row(n):
return ' '.join(['*'] * n)
rows = input('Number of rows: ')
if (nrows := int(rows)) > 0:
diamond = [make_row(nrows)]
j = len(diamond[0])
for i in range(nrows-1, 0, -1):
j -= 1
diamond.append(make_row(i).rjust(j))
print(*diamond[::-1], *diamond[1:], sep='\n')
Example:
Number of rows: 5
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*