Python Forum
Help with beginner problem?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with beginner problem?
#1
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!
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Beginner, problem with CS50 vanity plates problem Chief816 3 6,123 Apr-22-2023, 09:31 PM
Last Post: rob101

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020