0

我目前在初学者 python 类中,所以不要太用力....但是我根据随机生成的数字做文本模式,目前面临一个我无法弄清楚的问题

if random_num > 0:
        for j in range(random_num):
            for i in range(random_num):
                print("*"*(random_num-i))
            print()

这是我的代码的一部分,它根据已经生成的随机数创建三角形图案。我运行的结果是:

Do you wish to print another pattern (y/n)? y
Random Number:  4
****
***
**
*

****
***
**
*

****
***
**
*

****
***
**
*
````````````````````````````````````````````````````````````````````````````````````````````````````````
it prints the triangle how I want it by taking one off after every row but as you can see it prints itself same amount of times as number generated. anyone have any imput? also I cannot use "break"
4

2 回答 2

0

随机数 = 4

while random_num > 0:
  print('*'*random_num)
  random_num -= 1

将 while 循环视为一个 if 语句,它不断重复循环,直到条件不满足。

于 2021-03-04T04:38:12.297 回答
0

您不需要两个 for 循环。

一个循环将打印 n 行,其中 n 是 random_number。每行将有 n - i 个星号,其中 i 是行的索引——这是因为您将星号乘以 (random_number-1)。所以第 0 行将有 n - 0 = n 颗星,然后下一行将有 n - 1 颗星,依此类推。

于 2021-03-04T04:32:33.817 回答