Nested Loop to Generate Triangle

Peter Pearson pkpearson at nowhere.invalid
Thu May 25 12:55:37 EDT 2017


On Thu, 25 May 2017 09:28:31 -0700 (PDT), Victor Demelo wrote:
> I need the triangle to be in reverse. The assignment requires a nested
> loop to generate a triangle with the user input of how many lines.
>
> Currently, I get answers such as:
> OOOO
> OOO
> OO
> O
>
> When I actually need it to be like this:
> OOOO
>  OOO
>   OO
>    O
>
> I just need to get it flipped-over on the other side.
>
> Here is the code I have written, thank you.
>
> base_size = int(input("How many lines? "))
> columns = base_size
>  
> for row in range (base_size) :
>    for columns in range (columns) :
>        print('O', end='')
>    print()

Seems like you're close to a solution.  You just need to print
a certain number of spaces at the beginning of each line, right?

Warning: When you say

    for columns in range (columns) :

you're creating a confusing situation with the name "columns":
the original meaning, an integer equal to base_size, is now "shadowed"
by a new meaning.  This sort of thing tends to create trouble.  Besides,
you probably meant to say range(base_size), not range(columns).

I don't know how much you're supposed to know about Python basics,
but have you encountered expressions like 5*"Hello" yet?

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list