標籤:形參 ucid luci attach 函數 ons utils 逗號 its
1.編寫一個名為right_justify的函數,函數接受一個名為``s``的字串作為形參, 並在列印足夠多的前置空格(leading space)之後列印這個字串,使得字串的最後一個字母位於顯示屏的第70列。
def right_justify(s): length = len(s) lspace = 70 - length so = ‘ ‘ * lspace + s print(so)right_justify(‘dean‘)
2.函數對象是一個可以賦值給變數的值,也可以作為實參傳遞。例如, do_twice函數接受函數對象作為實參,並調用這個函數對象兩次:
def do_twice(f): f() f()
下面這個樣本使用do_twice來調用名為print_spam的函數兩次。
def print_spam(): print(‘spam‘)do_twice(print_spam)
- 將這個樣本寫入指令碼,並測試。
- 修改
do_twice,使其接受兩個實參,一個是函數對象,另一個是值。 然後調用這一函數對象兩次,將那個值傳遞給函數對象作為實參。
- 從本章前面一些的樣本中,將
print_twice 函數的定義複製到指令碼中。
- 使用修改過的
do_twice,調用print_twice兩次,將‘spam‘傳遞給它作為實參。
- 定義一個名為
do_four的新函數,其接受一個函數對象和一個值作為實參。 調用這個函數對象四次,將那個值作為形參傳遞給它。 函數體中應該只有兩條語句,而不是四條。 1def do_twice(f, g): 2 f(g) 3 f(g) 4 5 6 def print_twice(g): 7 print(g) 8 print(g) 9 10 11 def do_four(f, g):12 # for i in range(4):13 # f(g)14 do_twice(f, g)15 do_twice(f, g)16 17 18 do_twice(print_twice, ‘spam‘)19 print(‘‘)20 21 do_four(print_twice, ‘spam‘)
3.編寫一個能畫出如下網格(grid)的函數
-
+ - - - - + - - - - +| | || | || | || | |+ - - - - + - - - - +| | || | || | || | |+ - - - - + - - - - +
- 提示:你可以使用一個用逗號分隔的值序列,在一行中列印出多個值:
print(‘+‘, ‘-‘)
print 函數預設會自動換行,但是你可以阻止這個行為,只需要像下面這樣將行結尾變成一個空格:
print(‘+‘, end=‘ ‘)print(‘-‘)
1 def do_twice(f): 2 f() 3 f() 4 5 6 def do_four(f): 7 do_twice(f) 8 do_twice(f) 9 10 11 def print_beam():12 print(‘+ - - - -‘, end=‘ ‘)13 14 15 def print_post():16 print(‘| ‘, end=‘ ‘)17 18 19 def print_beams():20 do_twice(print_beam)21 print(‘+‘)22 23 24 def print_posts():25 do_twice(print_post)26 print(‘|‘)27 28 29 def print_row():30 print_beams()31 do_four(print_posts)32 33 34 def print_grid():35 do_twice(print_row)36 print_beams()37 38 39 print_grid()
day-1.python初學者練手題