Python中的星号艺术 [英] Asterisk art in python

查看:103
本文介绍了Python中的星号艺术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python生成这张图片!

I would like to produce this picture in python!

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

我输入了以下内容:

x=1
while x<10:
 print '%10s'    %'*'*x
 x=x+1

其中令人遗憾的是,似乎产生了由正确数量的点组成的某种事物,如上图所示,但是每个点星号都彼此隔开,而不是整体上合理。

Which sadly seems to produce something composed of the right number of dots as the picture above, but each of those dot asterisks are separated by spaced apart from one another, rather than justified right as a whole.

有人对如何实现自己想要的东西有聪明的主意吗?

Anybody have a clever mind on how I might achieve what I want?

推荐答案

 '%10s'    %'*'*x

被解析为

('%10s' % '*') * x

因为 * 运算符具有相同的优先级和gro从左到右 [文档] 。您需要添加括号,例如:

because the % and * operators have the same precedence and group left-to-right[docs]. You need to add parentheses, like this:

x = 1
while x < 10:
    print '%10s' % ('*' * x)
    x = x + 1

如果要遍历一个数字范围,则使用 for 循环比while循环更惯用。像这样:

If you want to loop through a range of numbers, it's considered more idiomatic to use a for loop than a while loop. Like this:

for x in range(1, 10):
    print '%10s' % ('*' * x)

为x in range(0,10)等同于Java或C中的 for(int x = 0; x <10; x ++)

for x in range(0, 10) is equivalent to for(int x = 0; x < 10; x++) in Java or C.

这篇关于Python中的星号艺术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆