Python Forum

Full Version: Help with beginner problem?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello! I'm a beginner at Python and the course was going smoothly at first for me, but now recursive/loop structure have come into play and it's been confusing me.
For one of my assignments, I need to create this triangle:
Output:
* * * * * * * * *
So here's the closest thing I've been able to get:
j=9
for i in range (1,10,2):
    if i % 3 or 5:
        print (' '* j+i * '*')
        j=j-1
which got me
Output:
* *** ***** ******* *********
and it looks hardly anything close to what I should be getting. How do I omit certain rows and insert spaces between the asterisks? Huh
**edit: the triangles are suppose to be in a pyramid shape and not in the staircase shape. I tried to space it out but it didn't seem to work!
Use python tags when posting code to preserve the indents, which are important. I added them (and output tags) for you this time. See the BBCode link in my signature below for how to do it yourself.

First, your if statement is wrong. i % 3 or 5 is equivalent to (i % 3) or (5), and 5 is always true. More details are here. You want i % 3 or i % 5.

Note that you don't want to exclude the other rows, you want to print blank rows instead. So you will want an else statement to print the blank row.

The simplest way to add the space in between the asterisks would be i * '* '. You could also do ' '.join(['*'] * i), which wouldn't leave a trailing space. Note that j would have be calculated differently with spaces, since the rows would be wider. Of course, you don't even need j. You can calculate j from i.