Exercises
Exercise 3-1.
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 # 前空格加上monty,要有70个字符
Hint: Use string concatenation and repetition. Also, Python provides a built-in function
called len that returns the length of a string, so the value of len(‘monty’) is 5
def right_justify(bruce):
print(' ' * (70 - len(bruce)) + bruce)
right_justify('monty')
# --------------------------------------------------------------------
monty
Exercise 3-2.
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 print_spam twice:
def print_spam():
print('spam')
do_twice(print_spam)
def print_spam():
print('spam')
def do_twice(f):
f()
f()
do_twice(print_spam)
#-------------------------
spam
spam
#--------
如果调用函数参数括号里的函数带括号会报错
do_twice(print_spam())
Traceback (most recent call last):
File "D:/share/python/test/test.py", line 14, in <module>
do_twice(print_spam())
File "D:/share/python/test/test.py", line 10, in do_twice
f()
TypeError: 'NoneType' object is not callable
def do_twice(arg):
print(arg)
print(arg)
def do_four(arg):
do_twice(arg)
do_twice(arg)
do_twice('123')
do_four('abc')
# -----------
123
123
abc
abc
abc
abc
Exercise 3-3.
Solution: http://thinkpython2.com/code/grid.py
# 自己写的没人家官方写的好,不贴自己的了
def do_twice(f):
f()
f()
def do_four(f):
do_twice(f)
do_twice(f)
def one_four_one(f, g, h):
f()
do_four(g)
h()
def print_plus():
print('+', end=' ')
def print_dash():
print('-', end=' ')
def print_bar():
print('|', end=' ')
def print_space():
print(' ', end=' ')
def print_end():
print()
def nothing():
"""do nothing"""
def print1beam():
one_four_one(nothing, print_dash, print_plus)
def print1post():
one_four_one(nothing, print_space, print_bar)
def print4beams():
one_four_one(print_plus, print1beam, print_end)
def print4posts():
one_four_one(print_bar, print1post, print_end)
def print_row():
one_four_one(nothing, print4posts, print4beams)
def print_grid():
one_four_one(print4beams, print_row, nothing)
print_grid()
# --------------------------
+ - - - - + - - - - + - - - - + - - - - +
| | | | |
| | | | |
| | | | |
| | | | |
+ - - - - + - - - - + - - - - + - - - - +
| | | | |
| | | | |
| | | | |
| | | | |
+ - - - - + - - - - + - - - - + - - - - +
| | | | |
| | | | |
| | | | |
| | | | |
+ - - - - + - - - - + - - - - + - - - - +
| | | | |
| | | | |
| | | | |
| | | | |
+ - - - - + - - - - + - - - - + - - - - +