Home > Enterprise >  Alternating lines with Nested Loops
Alternating lines with Nested Loops

Time:02-12

This is the exercise I need to complete: Using nested loops, write some code that outputs the following:

##########
**********
##########
**********
##########

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

for a in range (0, 5, 2): 
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")

CodePudding user response:

Since no input is specified, only a fixed output:

for _ in '_':
    for _ in '_':
        print('''##########
**********
##########
**********
##########''')

And yes, if that was my homework exercise, I'd absolutely submit this.

CodePudding user response:

I would suggest to simply base the symbol on the row index, even or odd

nb_lines = 5
line_size = 10

for i in range(nb_lines):
    for _ in range(line_size):
        if i % 2 == 0:
            print("#", end="")
        else:
            print("*", end="")
    print()

But no need of nested loops

nb_lines = 5
line_size = 10

for i in range(nb_lines):
    if i % 2 == 0:
        print("#" * line_size)
    else:
        print("*" * line_size)

CodePudding user response:

There are several ways to do it. First you should check how many lines you need to output. 5, so you need a loop doing something 5 times.

for i in range(5):

Now you need 2 loops to paste print the 2 line patterns (you already have them in your code)

 for b in range(10):
        print("#", end = "")
    print("")

and

for b in range(10):
        print("*", end = "")
    print("")

If you need to alternate between 2 values it's mostly the best to use the Modulo Operator.

So you can just switch between the 2 loops by % 2.

for i in range(5):
  if i % 2 == 0:
    for b in range(10):
        print("#", end = "")
    print("")
  else:
    for b in range(10):
        print("*", end = "")
    print("")

CodePudding user response:

def printStripes(row_length, number_of_rows):
    for _ in '_':
        print( "".join(
            [ "\n" if n%(row_length 1)==row_length else
              "#"  if (n//(row_length 1))%2==0 else
              "*"
              for n in range(number_of_rows*(row_length 1))
            ]
        ),end="")

printStripes(row_length=5,number_of_rows=8)

But don't tell your teacher that you got if from stackoverflow. (Thanks Kelly, for how to deal with the nested loop constraint.)

CodePudding user response:

You can use this to get the result that you want

for i in range(0,5):
     print("*"*10)
     print("#"*10)
  • Related