Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to do a board outline with "-" and "+" but I am getting unexpected output

I mentioned the condition to print at particular places but instead of printing at those locations code just appends "+" to "-" even with range condition it exceeds the limit.
I wanted to print "+" at 0, 8, 16, 24 index locations and print "-" in between them.

def display(board):
    for row in range(25):
        print("-", end = "")
        if row == 0 or row == 8 or row == 16 or row == 24:
            print("+", end = "")

The outcome when I invoke the function is:

-+--------+--------+--------+

I tried to modify code so that "+" stays in condition loop when "-" is outside but output is different

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def display(board):
    for row in range(25):
        if row == 0 or row == 8 or row == 16 or row == 24: 
            print("+", end = "")
        print("-", end = "")
+--------+--------+--------+-

My expected outcome is supposed to be:

+-------+-------+-------+

>Solution :

You’ve just got to use an if else to only print 1 char per iteration of your loop. Without the else, you are printing twice on each multiple of 8.

def display(board):
    for row in range(25):
        if row == 0 or row == 8 or row == 16 or row == 24:
            print("+", end = "")
        else
            print("-", end = "")

You could also simplify the code and make it a bit more readable using some math.

def display(board):
    for row in range(25):
        if row % 8 == 0:
            print("+", end = "")
        else
            print("-", end = "")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading