6

I would like to produce this picture in python!

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

I entered this:

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?

2
  • 8
    what about Obelix? Commented Sep 5, 2011 at 12:52
  • 3
    3 edits and none have corrected Asterix->Asterisk =) Commented Sep 5, 2011 at 12:53

5 Answers 5

13
 '%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.

Sign up to request clarification or add additional context in comments.

2 Comments

Superb! Walla! What a nice answer! Thank you so much - works perfectly! - this is the first answer I see so I'm commenting to thank you but of course many many thanks to everyone else! My deepest appreciation of course!
I think you mean "Voila!", French for "There it is!", "Presto!", or "Woot, doggie!"
8

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, '-').

Comments

2

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

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

Comments

1
print '\n'.join(' ' * (10 - i) + '*' * i for i in range(10))

Comments

1

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

for i in range(1, 11):
    print "%10s"%('*' *i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.