简体   繁体   中英

Creating a table on Python using nested loops

While creating a table on python, I ran into an issue. Here is the code:

row = 5
col = 4
for x in range(1, row + 1):
    print("Row", x, end="")
    for y in range(1, col + 1):
        print(" Column", y, end="")
        print(" Row", x, end="")
    print()

This is what runs:

Row 1 Column 1 Row 1 Column 2 Row 1 Column 3 Row 1 Column 4 Row 1
Row 2 Column 1 Row 2 Column 2 Row 2 Column 3 Row 2 Column 4 Row 2
Row 3 Column 1 Row 3 Column 2 Row 3 Column 3 Row 3 Column 4 Row 3
Row 4 Column 1 Row 4 Column 2 Row 4 Column 3 Row 4 Column 4 Row 4
Row 5 Column 1 Row 5 Column 2 Row 5 Column 3 Row 5 Column 4 Row 5

As you can see it ends with rows and is missing column 5. What can I do to fix this?

This is the output that I expect:

Row 1 Column 1 Row 1 Column 2 Row 1 Column 3 Row 1 Column 4 Row 1 Column 5
Row 2 Column 1 Row 2 Column 2 Row 2 Column 3 Row 2 Column 4 Row 2 Column 5
Row 3 Column 1 Row 3 Column 2 Row 3 Column 3 Row 3 Column 4 Row 3 Column 5
Row 4 Column 1 Row 4 Column 2 Row 4 Column 3 Row 4 Column 4 Row 4 Column 5
Row 5 Column 1 Row 5 Column 2 Row 5 Column 3 Row 5 Column 4 Row 5 Column 5

Following code should do it:-

row = 5
col = 5
for x in range(1, row + 1):
    for y in range(1, col + 1):
        print(" Row", x, end="")
        print(" Column", y, end="")
    print()

Question is, you have initiated column as 4 and why do you expect it to print "Column 5". Is it something you want or is there something wrong with the logic you are trying to convey?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM