【问题标题】:How to stop this from repeating?如何阻止这种情况重复发生?
【发布时间】:2021-03-04 04:24:01
【问题描述】:

我目前在初学者 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"

【问题讨论】:

  • 尝试在print()之后添加random_num -= 1

标签: loops if-statement number-formatting textpattern


【解决方案1】:

你不需要两个 for 循环。

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

【讨论】:

    【解决方案2】:

    随机数 = 4

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 2012-03-09
      • 2021-10-22
      相关资源
      最近更新 更多