Creating a table with nested loops in python

Question:

I’m learning abort nested loops and I’ve gotten an assignment to create a function that takes two integer inputs. Then it should create something like in this image. Only problem is that when I use an odd number for columns it doesnt work.

It has to be an "advanced nested loop" for the assignment to be approved.

def createTable(rows, columns):
    rows = int(input("Enter number of rows: "))
    columns = int(input("Enter number of columns: "))

    for row in range(rows):
        if row%2 == 0:              
            for col in range(0, columns):
                if col%2 == 1:
                    if col != columns - 1:
                        print(" ", end="")
                    else:
                        print(" ")
                else:
                    print("|", end="")
        else:
            print("-" * (columns - 1))
            
    return True

createTable(1, 2)

Asked By: Psmacks

||

Answers:

I have made one iteration of the code which you want. It prints the correct output for even and odd number of rows and columns. It is very similar to the outputs you want. When you provide further clarification for your question, I can provide an updated code.

rows = 20
columns = 41

for i in range(rows):
    if i%2 == 0:
        output = "| " * (columns//2)
        print(output)
    else: 
        output = "-" * ((columns//2)*2 - 1)
        print(output)    

The output can be visualised below. Hope this solves your query.

enter image description here

Based on the code provided by the question provider, I have edited the code and the following code will work in the same manner as you want it to with nested loops.

def createtable(rows, columns): 
    for row in range(rows):
        if row%2 == 0:              
            for col in range(0, ((columns+1)//2)*2, 2):
                print("| ", end="")
            print()
        else:
            print("-" * (((columns+1)//2)*2 - 1))

    return True

Tested for both these cases.

createTable(20, 40)
createTable(20, 41)
createTable(2, 1)
Answered By: Prakhar Rathi
def createTable(rows, columns):
    rows = int(input("Enter number of rows: "))
    columns = int(input("Enter number of columns: "))

    for row in range(rows):
        if row%2 == 0:              
            for col in range(0, columns):
                if col%2 == 1:
                    if col != columns - 1:
                        print(" ", end="")
                    else:
                        print(" ")
                else:
                    print("|", end="")
        else:
            print("-" * (columns - 1))
            
    return True
Answered By: user20536025
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.