Heisenberg
Heisenberg

Reputation: 115

how to print star hypen pattern in python

How to print the pattern like this:

(need to print n-1 lines)

input=3

----@
--@-@-@

input=6

----------@
--------@-@-@
------@---@---@
----@-----@-----@
--@-------@-------@

My code:

row = int(input())
for i in range(1, row):
    for j in range(1,row-i+1):
        print("-", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("@", end="")
        else:
            print("-", end="")
    print()

MY OUTPUT: input=5

----@
---@-@
--@---@
-@-----@

Please explain how to do??

Upvotes: 0

Views: 135

Answers (2)

WTler
WTler

Reputation: 26

row = int(input())
for i in range(1, row):
    for j in range(1,2*(row-i)+1):
        print("-", end="")
    for j in range(1, 4*i):
        if j==1 or j==2*i-1 or j==4*i-3:
            print("@", end="")
        elif j<=4*i-3:
            print("-", end="")
    print()

Upvotes: 0

Shinra tensei
Shinra tensei

Reputation: 1293

There are a few things missing and to be improved in your code:

  • There's no need to make a loop to print the same character again and again: on python you can use the product to repeat the character an x number of times. For example: "-" * 3 == "---"
  • They way you calculate the hyphens in the middle is fine, but you need to do it twice and add an "@" in between.
  • You can build the strings part by part first and then print the whole line, avoiding having to print an empty line in the end of the loop.
  • Personally, since the first line is going to have one "@" and not three, I prefer to calculate it and print it separately.

With these improvements, a solution to your problem could be:

row = int(input())
print("-" * (row - 1) * 2 + "@")
for i in range(row - 2, 0, -1):
    left_hyphens = "-" * i * 2
    mid_hyphens = "-" * (1 + 2 * (row - 2 - i))
    print(left_hyphens + "@" + mid_hyphens + "@" + mid_hyphens + "@")

Upvotes: 2

Related Questions