Reputation: 11
n=int(input('enter no of rows\n'))
for row in range(0,n):
for col in range(0,n):
if row==0 or col==(n-1):
print("A",end="")
else:
print(end="")
print()
i need output like below .im not getting it .can anyone help me on it , is there any problem with code .
AAAAA
A A
A A
AA
A
Upvotes: 1
Views: 56
Reputation: 7812
You can use python "feature" and do it with 1 loop:
n = int(input('enter no of rows\n'))
print("A" * n)
for row in range(n - 2):
print(" " * (row + 1) + "A" + " " * (n - row - 3) + "A")
print(" " * (n - 1) + "A")
Why does it work?
First of all, let's take look on result you want to achieve. You want to print in console triangle built with symbols A
.
To create algorithm with loop we should find something common in each printed line. Let's take a look on output again:
0 row: AAAAA # no spaces, 5 'A' chars
1 row: A A # 1 space + 'A' + 2 spaces + 'A'
2 row: A A # 2 spaces + 'A' + 1 space + 'A'
3 row: AA # 3 spaces + 'A' + 0 spaces + 'A'
4 row: A # 4 spaces + 'A'
I've added some comments to show how I analyze this output. Here we see that first and last lines dont follow same logic with others. So let's print them outside loop. Now let's try to create algorithm for building "central" rows:
row index
;amount of rows
- row index
- 2
(total length of each row should equal amount of rows
; we should minus 2
, cause except spaces we print 2 'A' chars);In python multiplication of string and int creates new string copied amount of times provided in int value. Example: "A" * 10
will return new string "AAAAAAAAAA"
. We will use this trick in code.
Now let's code. First of all let's print first line, which contains 'A' symbol repeated n
times:
print("A" * n)
Then let's write loop. In my code I've used range()
with 1 argument. But we should remember that we've already printed 0 row and should start from 1. In my code it's not so clear, so let's do it in other way:
for row in range(1, row - 1):
Now let's write code for printing row:
print(" " * row # amount of spaces equals row index
+ "A" # 'A' char
+ " " * (n - row - 2) # amount of spaces between 'A' chars equals
# length of row - row index - 2
+ "A") # 'A' char
And finally print last line:
print(" " * (n - 1) # amount of spaces on the start of last line
# equals length of row - 1
+ "A") # 'A' char
And full code:
print("A" * n)
for row in range(1, row - 1):
print(" " * row # amount of spaces equals row index
+ "A" # 'A' char
+ " " * (n - row - 2) # amount of spaces between 'A' chars equals
# length of row - row index - 2
+ "A") # 'A' char
print(" " * (n - 1) # amount of spaces on the start of last line
# equals length of row - 1
+ "A") # 'A' char
Upvotes: 0
Reputation: 7206
If you want to use your way:
n=int(input('enter no of rows\n'))
for row in range(0,n):
for col in range(0,n):
if row == 0 or col == (n-1) or row == col:
print ("A",end ="")
else:
print(" ", end ="")
print()
output:
enter no of rows
5
AAAAA
A A
A A
AA
A
Upvotes: 1