Python Programming Exercises, Gently Explained
86
Solution Design
There are three separate parts required for the drawBorder() function: drawing the top border
line, drawing the middle, and drawing the bottom border line. The code for drawing the top and
bottom border line will be identical. So really, there’s only two parts you need to code in this function.
Drawing the top horizontal line involves creating a string with a + plus character on the left,
followed by a number of - minus characters, and then another + plus character on the right. The
number of - minus characters needed is width - 2, because the two + plus characters for the
corners count as two units of width.
Similarly, drawing the middle rows requires a | pipe character, followed by a number of space
characters, and then another | pipe character. The number of spaces is also width - 2. You’ll also
need to put this code in a for loop, and draw a number of these rows equal to height - 2.
Finally, drawing the bottom horizontal line is identical to drawing the top. You can copy and
paste the code.
String replication can easily create the - minus and space character strings. In Python, you can
use the * operator with a string and an integer to evaluate to a longer string. For example, enter the
following into the interactive shell:
>>> 'Hello' * 3
'HelloHelloHello'
>>> '-' * 16
'----------------'
>>> width = 10
>>> (width - 2) * '-'
'--------'
Special Cases and Gotchas
Note that the minimum width and height for a border is 2. Calling drawBorder(2, 2) should
print the following on the screen:
++
++
If either the width or height argument is less than 2, the function prints nothing.
Now try to write a solution based on the information in the previous sections. If you still have
trouble solving this exercise, read the
Solution Template section for additional hints.
Dostları ilə paylaş: