我正在try 这个问题,我只需要使用下面给出的代码来制作这个三角形图案:

*
***
*****
*******
*********

the blanks should be filled with the codes below

以下是允许使用的代码:

count += 1
star = "*"
continue
count = 10
elif:
print (star,end="")
print()
print (star)
break 
i % 2 == 0
i % 2 == 1

这是我设法做的,我似乎找不到一种方法来获得上面的输出与代码:

count=10
star="*"
for i in range (count):
    if i%2==0:
        print(star)
    else:
        for x in range (i):
            print(star,end="*")
        count+=1

推荐答案

好的,首先要做的是:你在第一行中的定义是正确的:

count=10
star="*"
for i in range(count):

如果你仔细观察这个图案,你就会注意到,如果你仔细观察这个图案,每一条线都是由奇数颗星星组成的:1,3,5……所以从根本上说,你想跳过每一次有偶数颗星的迭代,这就是continue的意义所在,把你带到下一个迭代循环. 但是请记住,Pythonrange迭代从0开始,所以每一行都比它的索引多包含一个星号.总而言之,you want to print even lines (with an odd number of stars) and skip odd lines (with an even number of stars)项:

if (i%2 == 1):      # if you're looking at an odd line (with an even number of stars)
    continue        # skip this iteration
else:               # we're now sure we're on an even line

现在我们只有偶数线了.对于这些行中的每一行,我们希望保留与行索引(i索引)+1一样多的星号.当使用print方法时,end的缺省值是\n,这是换行符,所以当您使用print时,默认情况下它打印一行并转到下一行.print(star, end="")指令将通过强制代码保持在同一行而不是转到新行来帮助我们.还记得我们说过我们想打印(i+1)颗星星吗?

for x in range(i):
            print(star,end="")    #print our star and prevents the new line
        print(star)               #once we printed our i stars, we print the i+1 and go to a new line

总而言之:

count=10
star="*"
for i in range (count):
    if (i%2 == 1):      # if you're looking at an odd line (with an even number of stars)
        continue        # skip this iteration
    else:               # we're now sure we're on an even line
        for x in range(i):
            print(star,end="")    #print our star and stay on the same line
        print(star)               #once we printed our i stars, we print the i+1 and go to a new line

Python相关问答推荐

更改matplotlib彩色条的字体并勾选标签?

使用FASTCGI在IIS上运行Django频道

使用新的类型语法正确注释ParamSecdecorator (3.12)

max_of_three使用First_select、second_select、

使用miniconda创建环境的问题

_repr_html_实现自定义__getattr_时未显示

如果值不存在,列表理解返回列表

为什么这个带有List输入的简单numba函数这么慢

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

numpy卷积与有效

NumPy中条件嵌套for循环的向量化

使用Python从URL下载Excel文件

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

Pandas Data Wrangling/Dataframe Assignment

下三角形掩码与seaborn clustermap bug

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

Autocad使用pyautocad/comtypes将对象从一个图形复制到另一个图形

如何编辑此代码,使其从多个EXCEL文件的特定工作表中提取数据以显示在单独的文件中

如何让PYTHON上的Selify连接到现有的Firefox实例-我无法连接到Marionette端口

为什么这个正则表达式没有捕获最后一次输入?