简体   繁体   English

如何在python中并排打印星号三角形?

[英]How to print asterisk triangles side-by-side in python?

I am trying to print 4 star triangle side-by-side using nested for-loops in python.我正在尝试使用 python 中的嵌套 for 循环并排打印 4 个星形三角形。 I included the code I am using now that prints the triangles vertically, but I do not know how to print them horizontally.我包含了我现在使用的垂直打印三角形的代码,但我不知道如何水平打印它们。

n = 0

print ("Pattern A")
for x in range (0,11):
    n = n + 1
    for a in range (0, n-1):
        print ('*', end = '')
     print()
print ('')
print ("Pattern B")
for b in range (0,11):
    n = n - 1
    for d in range (0, n+1):
        print ('*', end = '')
    print()
print ('')

enter image description here在此处输入图片说明

maximum = 10
a, b, c, d = 1, maximum, maximum, 1


while a <= maximum:
    print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c  + ' '*2 + '*'*d + ' '*(maximum-d))
    a += 1
    d += 1
    b -= 1
    c -= 1

Thanks to @AzBakuFarid the main idea is to print every line of shapes from the top to the last together.感谢@AzBakuFarid 的主要想法是打印从顶部到最后的每一行形状。 @AzBakuFarid code had a very little mistake that you can see the corrected one below : @AzBakuFarid 代码有一个很小的错误,您可以在下面看到更正的错误:

maximum = 10
a, b, c, d = 1, maximum, maximum, 1

while a <= maximum:
    print('*'*a + ' '*(maximum-a) + ' '*2 + '*'*b + ' '*(maximum-b) + ' '*2 + ' '*(maximum-c) + '*'*c  + ' '*2 +  ' '*(maximum-d) + '*'*d)
    a += 1
    d += 1
    b -= 1
    c -= 1

As u wanted to be with for-loops I came up with this :因为你想使用 for 循环,所以我想出了这个:

longest = int(input())
asterisk_a = 1
spaces_a = longest - 1
asterisk_b = longest
spaces_b = 0
asterisk_c = longest
spaces_c = 0
asterisk_d = 1
spaces_d = longest - 1
for i in range(0,longest):
    print(asterisk_a * '*' + spaces_a * ' ' + '  ' + asterisk_b * '*' + spaces_b * ' ' + '  ' + spaces_c * ' ' +  asterisk_c * '*' + '  ' + spaces_d * ' ' +  asterisk_d * '*')
    asterisk_a += 1
    spaces_a -= 1
    asterisk_b -= 1
    spaces_b += 1
    asterisk_c -= 1
    spaces_c += 1
    asterisk_d += 1
    spaces_d -= 1

In the first line you should give the number of asterisks in the longest case.在第一行中,您应该给出最长情况下星号的数量。 I tried to use meaningful variable names for better understanding.我尝试使用有意义的变量名来更好地理解。

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

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