本週Python 08 學習-如何結構化我們的程式。
我們學習過基本的函數(function),但是很少用;現在就是時候,讓我們學習如何搭配main function 讓我們的程式具有結構化! 這是 Python 基礎學習上學習最後第二堂課了...
從輝今天跟大家分享了檔案讀寫的方法,以下是今天的範例:
#!/usr/bin/env python3 # input a file & open it while True: try: filename = input('To read a file: ') ofile = open(filename, 'rt') except: print('incorrect file, try again: ') continue break # print(ofile.read()) collection = [] word_bank = {} count_word = [] # collect each characters in ofile for line in ofile: cline = line.strip().split() for letter in cline: if not letter.isalpha(): continue collection.append(letter.lower()) for word in collection: word_bank[word] = word_bank.get(word, 0) + 1 # Sort word by alphabeta in word_bank """ 利用 dic.items 來去處key, value 並在count_word 中排序。 list 可以使用的手段比較多,所以我選擇list """ for key, value in word_bank.items(): count_word.append((key, value)) count_word.sort() # Write to a file wfile = input('Given an output file name: ') with open(wfile, 'wt') as output_file: print('Arranged by alphabet:', file=output_file) print('Words: Counting', file=output_file) for key, value in count_word: print(key, value, file=output_file) # close the file ofile.close()
這個程式是由缺陷的,大家有發現嗎?
這是coursera.org 上 "Learn to Program: The Fundamentals" by Jennifer Campbell, Paul Gries 的教學影片 這是coursera.org 上 "Learn to Program: The Fundamentals" by Jennifer Campbell, Paul Gries 的教學影片 Dictionary, list & function
本週從輝講解dictionary 並透過範例來複習for loop, list。課堂中的範例是來自Pyschool 的一個聯繫。
題目: mRNA 一般是由 DNA 轉譯過來的。DNA 的4對核酸A, T, C, G 與mRNA 的核酸有一對一的對應。 本週我們開始進入「用範例」來上課的新的教室互動,並用接龍或是集體brain storming 在從輝老師的帶領下完成一個小的習題。希望大家喜歡這樣的教學互動。 以下是3/27 的心得筆記: 1. Python 03 的課程範疇是if 的用法,因此我們從一個習題出發來學習。 習題: 輸入一組數字直到遇到關鍵字 "done" 才能停止輸入,並要判斷輸入數值的最大和最小值。利用try/except 來避免無效的輸入。 2. 利用接龍遊戲,讓大家練習思考寫code 的邏輯流程 3. 我們也學習到有關ipython 的技巧:
4. 課程中的範例提示:
|
Categories
All
Archives
October 2015
桃花源講堂桃花源講堂是桃園支聯會成員學習、成長的園地! |