Asterisk art in python

前端 未结 5 1090
遇见更好的自我
遇见更好的自我 2020-12-20 21:10

I would like to produce this picture in python!

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


        
相关标签:
5条回答
  • 2020-12-20 21:51
     '%10s'    %'*'*x
    

    is being parsed as

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

    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
    

    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)
    

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

    0 讨论(0)
  • 2020-12-20 21:56

    It's because of the operator precedence, use this one:

    x=1
    while x<10:
     print '%10s' % ('*'*x)
     x=x+1
    
    0 讨论(0)
  • 2020-12-20 21:57

    To be exact, as your picture ends with 10 asterisks, you need.

    for i in range(1, 11):
        print "%10s"%('*' *i)
    
    0 讨论(0)
  • 2020-12-20 22:04
    print '\n'.join(' ' * (10 - i) + '*' * i for i in range(10))
    
    0 讨论(0)
  • 2020-12-20 22:11

    string object has rjust and ljust methods for precisely this thing.

    >>> n = 10
    >>> for i in xrange(1,n+1):
    ...   print (i*'*').rjust(n)
    ... 
             *
            **
           ***
          ****
         *****
        ******
       *******
      ********
     *********
    **********
    

    or, alternatively:

    >>> for i in reversed(xrange(n)):
    ...   print (i*' ').ljust(n, '*')
    ... 
             *
            **
           ***
          ****
         *****
        ******
       *******
      ********
     *********
    **********
    

    My second example uses a space character as the printable character, and * as the fill character.

    The argument to ljust or rjust is the terminal width. I often use these for separating sections with headings when you have chatty debug printout, e.g. print '--Spam!'.ljust(80, '-').

    0 讨论(0)
提交回复
热议问题