day-1.python初學者練手題

來源:互聯網
上載者:User

標籤:形參   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)
  1. 將這個樣本寫入指令碼,並測試。
  2. 修改do_twice,使其接受兩個實參,一個是函數對象,另一個是值。 然後調用這一函數對象兩次,將那個值傳遞給函數對象作為實參。
  3. 從本章前面一些的樣本中,將 print_twice 函數的定義複製到指令碼中。
  4. 使用修改過的do_twice,調用print_twice兩次,將‘spam‘傳遞給它作為實參。
  5. 定義一個名為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)的函數

  6.       
    + - - - - + - - - - +|         |         ||         |         ||         |         ||         |         |+ - - - - + - - - - +|         |         ||         |         ||         |         ||         |         |+ - - - - + - - - - +
  7. 提示:你可以使用一個用逗號分隔的值序列,在一行中列印出多個值:
  8. print(‘+‘, ‘-‘)
  9. print 函數預設會自動換行,但是你可以阻止這個行為,只需要像下面這樣將行結尾變成一個空格:
  10. print(‘+‘, end=‘ ‘)print(‘-‘)
  11.  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初學者練手題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.