Skip to content Skip to sidebar Skip to footer

Iteration In Python

Hi I would like create some code which will print a box that looks like this + -- + -- + -- + -- + -- + | | | | | | + -- + -- + -- + -- + -- + The code should us

Solution 1:

You can do this with a combination of using the * operator to make a string of characters, and join to add delimiters between those characters.

def printBoxes(boxes):
    edges = ' -- '.join('+' * (boxes+1))
    middle = '    '.join('|' * (boxes+1))
    print(edges)
    print(middle)
    print(edges)

Testing

>>> printBoxes(3)
+ -- + -- + -- +
|    |    |    |
+ -- + -- + -- +

>>> printBoxes(5)
+ -- + -- + -- + -- + -- +
|    |    |    |    |    |
+ -- + -- + -- + -- + -- +

Solution 2:

I think the way your teacher wants you to solve this is by using the for loop to build up the three lines, box by box, and then print all three lines. Or, noticing that the top and bottom are the same, just use the same line for each:

edge, middle = '+', '|'for i in range(5):
    edge += ' -- +'
    middle += '    |'print(edge)
print(middle)
print(edge)

However, the answers using the * string repetition operator and/or the join method are much more Pythonic. If you can explain to your teacher how they work, and why they're better, and if your teacher isn't overly rigid (or stupid), that might be worth doing. Even if you don't want to try that, learning why they're better on your own may be worth doing.

Solution 3:

defprintBoxes(n):
    top = "+--" * n + "+"
    middle = "|  " * n + "|"print(top)
    print(middle)
    print(top)

printBoxes(5)

Post a Comment for "Iteration In Python"