Home > OS >  how can I convert the for-while loop into a for-for loop and achieve the same output?
how can I convert the for-while loop into a for-for loop and achieve the same output?

Time:03-25

This code successfully prints a youtube play button

rows = 6
symbol = '\U0001f34a'

for i in range(rows):
    for j in range(i 1):
        print('{' symbol '}', end = '')
    print()

for x in range(rows):   
    while x < 5:
        print('{' symbol '}', end = '')
        x =1

    print()
    

I tried to change the while loop into a for loop and print a "upside-down" right triangle. but it doesnt work.

rows = 6
symbol = '\U0001f34a'

for i in range(rows):
    for j in range(i 1):
        print('{' symbol '}', end = '')
    print()

for x in range(rows):   
    for x in range(5):
        print('{' symbol '}', end = '')

    print()
    

CodePudding user response:

Your second loop is always in range(5) so it will not print the desired output.

Firstly, you can use your 1st loop to set up the second, but it will be the same as above, and wont make a descending order. In order to do that, I reversed the 1st range :

for x in range(rows)[::-1]:  # Reverse the range
    for y in range(x):       # Use 1st loop variable as parameter
        print('{' symbol '}', end = '')

Output, with a 'O' since I didnt set up the encoding for your symbol

{O}
{O}{O}
{O}{O}{O}
{O}{O}{O}{O}
{O}{O}{O}{O}{O}
{O}{O}{O}{O}{O}{O}
{O}{O}{O}{O}{O}
{O}{O}{O}{O}
{O}{O}{O}
{O}{O}
{O}

CodePudding user response:

It was fun to create, so here is my code that works. The second for loop start to max length and end at 0 with a step of -1, with this you can create a for loop that decreases

    for i in range(rows):
        print('{' symbol '}'*(i 1))
    for i in range(rows,0,-1):
        print('{' symbol '}'*(i-1))
  • Related