Exercises
Exercise 1
Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5.
Write a function named right_justify" that takes a string named word as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
>>> right_justify('allen')
allenExercise 2
This exercise can be done using only the statements and other features we have learned so far.
Write a function
two_by_two_gridthat draws a grid like the following:
+ - + - +
| | |
+ - + - +
| | |
+ - + - +Hint: to print more than one value on a line, you can print a comma-separated sequence like print('+', '-').
In order to build a string spanning several lines, we can use the string character '\n' which represents the newline character. The newline character can be embedded in a string, or can be concatenated using the + operator as shown in the following examples.
A print statement all by itself ends the current line and goes to the next line.
Answer
Note: this is not a very good solution, a better approach is used in the solution for the function four_by_four_grid.
Write another function
four_by_four_gridto draw a similar grid with four rows and four columns.
Answer
Note: This solution is better than the one given for the function two_by_two_grid. It is important to familiarise ourselves with manipulating string to build the expected output.
Write a more generic function
x_by_y_grid(rows, cols)that draws a similar grid withrowsrows andcolscolumns.
Last updated