简体   繁体   English

如何在 python 中打印星号 hypen 图案

[英]how to print star hypen pattern in python

How to print the pattern like this:如何打印这样的图案:

(need to print n-1 lines ) (需要打印n-1

input=3输入=3

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

input=6输入=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我的 OUTPUT:输入=5

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

Please explain how to do??请解释如何做??

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.无需循环即可一次又一次地打印相同的字符:在 python 上,您可以使用该产品将字符重复 x 次。 For example: "-" * 3 == "---"例如: "-" * 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 + "@")
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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM