Write a function named
right_justify that takes a string named
s 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('monty') monty
Use string concatenation and repetition. Also, Python provides a built-in function called
lenthat returns the length of a string, so the value of
A function object is a value you can assign to a variable or pass as an argument. For example,
do_twice is a function that takes a function object as an argument and calls it twice:
def do_twice(f): f() f()
Here’s an example that uses
do_twice to call a function named
def print_spam(): print('spam') do_twice(print_spam)
- Type this example into a script and test it.
do_twiceso that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
- Copy the definition of
print_twicefrom earlier in this chapter to your script.
- Use the modified version of
'spam'as an argument.
- Define a new function called
do_fourthat takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
Note: This exercise should be done using only the statements and other features we have learned so far.
- Write a function that draws a grid like the following:
+ - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - +
Hint: to print more than one value on a line, you can print a comma-separated sequence of values:
print('+', end=' ') print('-')
The output of these statements is '+ -' on the same line. The output from the next print statement would begin on the next line.
- Write a function that draws a similar grid with four rows and four columns.
This exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly Media, 1997.