See More

{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "前言:基本上這是codeacademy的學習筆記,\n", "https://www.codecademy.com/\n", "\n", "原始版本是2.7版,現改為3.x 版,主要差異請參考:\n", "https://docs.python.org/3/whatsnew/3.0.html\n", "\n", "[Python/第一次用就上手](http://wiki.python.org.tw/Python/%E7%AC%AC%E4%B8%80%E6%AC%A1%E7%94%A8%E5%B0%B1%E4%B8%8A%E6%89%8B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Syntax" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "print 指令:print 字串; print 變數; print 字串, 變數, etc\n", "注解:python 3.5版改為函數 print()" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Welcome to Python!\n" ] } ], "source": [ "print(\"Welcome to Python!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "變數賦值:變數 = 值\n", "\n", "變數型態:整數(Integer), 浮點數(float), boolean(True/False)\n", "\n", "程式中變數可以隨時更改其值, 在Python中, 甚至可以更改變數型態" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my_int = 10 my_float = 0.123 my_bool = True\n", "my_var = 10\n", "my_var = False\n" ] } ], "source": [ "my_int = 10\n", "my_float = 0.123\n", "my_bool = True\n", "print(\"my_int =\", my_int, \"my_float = \",my_float, \"my_bool =\",my_bool)\n", "my_var = 10\n", "print(\"my_var = \", my_var)\n", "my_var = False\n", "print(\"my_var = \", my_var)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "縮排:Python中是以縮排來區分層級, 例如函數定義, 迴圈等等\n", "\n", "底下是一個縮排的例子, def 是在定義一個函數" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n" ] } ], "source": [ "def spam():\n", " eggs = 12\n", " return eggs\n", " \n", "print(spam())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "註解:一般單行註解或是在行尾註解可以使用#, 若要多行註解則以\"\"\"開頭,\"\"\"結尾" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "數學:加減乘除四則運算符號是一般常用符號, 次方則改為\\** 而不是^, 同餘則是 %" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1+2+3+4*5 = 26\n", "2^3 = 8\n", "3 %2 = 1\n" ] } ], "source": [ "print(\"1+2+3+4*5 = \", 1+2+3+4*5 )\n", "print(\"2^3 = \", 2**3)\n", "print(\"3 %2 =\", 3%2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# STRINGS AND CONSOLE OUTPUT" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "字串的定義方式是以雙引號或是單引號夾起來" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Graham\n", "John\n" ] } ], "source": [ "caesar = \"Graham\"\n", "praline = 'John'\n", "print(caesar)\n", "print(praline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Escaping characters:有些字元有特殊用途, 所以出現在字串中時必須加入反斜線\\" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This isn't flying, this is falling with style!\n", "\" is another special character.\n" ] } ], "source": [ "print('This isn\\'t flying, this is falling with style!')\n", "print(\"\\\" is another special character.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "字串可以視為一個array, 所以可以使用index挑出字串中特定幾個字元. 注意index由0開始" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The whole string is STRINGS and the first character is S . The last characters are NGS\n" ] } ], "source": [ "my_str = \"STRINGS\"\n", "print(\"The whole string is \",my_str,\" and the first character is \", my_str[0], \". The last characters are \",my_str[-3:])" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "與字串相關的幾個函數:\n", "\n", "len(mystr):傳回字串mystr的長度\n", "\n", "mystr.lower():將字串mystr都改為小寫\n", "\n", "mystr.upper():將字串mystr都改為大寫\n", "\n", "str(mynum):將mynum(數值或是數值變數)轉為字串" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The length of my_str is 11\n", "The effect of upper on my_str is MATHEMATICS\n", "The effect of lower on my_str is mathematics\n", "The third character of the 12345 is 3\n" ] } ], "source": [ "my_str = \"Mathematics\"\n", "print(\"The length of my_str is\", len(my_str))\n", "print(\"The effect of upper on my_str is\", my_str.upper())\n", "print(\"The effect of lower on my_str is\", my_str.lower())\n", "print(\"The third character of the 12345 is\", str(12345)[2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "字串可以用+這個運算連接起來, 注意連起來後的字串在原先的字串間沒有空白" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Spam and eggs\n", "Spamand eggs\n" ] } ], "source": [ "print( \"Spam \"+\"and \"+\"eggs\")\n", "str1 = \"Spam\"\n", "str2 = \"and\"\n", "str3 = \" eggs\"\n", "print(str1+str2+str3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 格式化字串/輸出" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "我們經常會碰到同類型的句子(更換部份名詞)一再出現的情形, 可以在字串中以%s 表示之後要取代的位置, 字串後%後的內容表示要取代%s的內容" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Let's not go to Camelot. 'Tis a silly place.\n", "Let's not go to Camelot. 'Tis a silly place.\n" ] } ], "source": [ "string_1 = \"Camelot\"\n", "string_2 = \"place\"\n", "my_str = \"Let's not go to %s. 'Tis a silly %s.\"\n", "print(\"Let's not go to %s. 'Tis a silly %s.\" % (string_1, string_2))\n", "print(my_str % (string_1, string_2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 輸入input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "my_str=input(\"Display Message\") 顯示\"Display Message\"後, 要求輸入資訊, 將結果賦予my_str. 注意中文輸入部份有點複雜, 等到我們有點基礎後再進行, (已改為 3.x版本,2.7版為raw_input) \n", "\n", "另外請注意底下的例子, 由於太長所以使用\\斷行" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your name?mhchen\n", "What is your quest?holy shit\n", "What is your favorite color?blue\n", "Ah, so your name is mhchen, your quest is holy shit, and your favorite color is blue.\n" ] } ], "source": [ "name = input(\"What is your name?\")\n", "quest = input(\"What is your quest?\")\n", "color = input(\"What is your favorite color?\")\n", "\n", "print(\"Ah, so your name is %s, your quest is %s, \" \\\n", "\"and your favorite color is %s.\" %(name, quest, color))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Date and Time" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "如果需要使用datetime功能時, 需引入datetime模組:from datetime import datetime\n", "\n", "datetime.now():傳回的是現在的時間日期, 如果需要其中的年月日時分等資訊可以使用 .year, .month, .day, .hour, .minute, .second" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2016-12-08 01:52:34.702193\n", "2016\n", "12\n", "8\n", "12/8/2016 1:52:34\n" ] } ], "source": [ "from datetime import datetime\n", "now = datetime.now()\n", "print(now)\n", "print( now.year)\n", "print( now.month)\n", "print( datetime.now().day)\n", "print( '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year,now.hour, now.minute, now.second))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conditionals & Control Flow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "底下的例子中定一了一個函數clinic, 注意函數結束的位置, 同時在主程式中如何呼叫clinic, 還有遞迴呼叫函數的部份.\n", "在這個小節中,重點是在control flow, 也就是if-elif-else的部份, 注意縮排以及冒號的位置" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "You've just entered the clinic!\n", "Do you take the door on the left or the right?\n", "Type left or right and hit 'Enter'.R\n", "Of course this is the Argument Room, I've told you that already!\n" ] } ], "source": [ "def clinic():\n", " print( \"You've just entered the clinic!\")\n", " print( \"Do you take the door on the left or the right?\")\n", " answer = input(\"Type left or right and hit 'Enter'.\").lower()\n", " if answer == \"left\" or answer == \"l\":\n", " print (\"This is the Verbal Abuse Room, you heap of parrot droppings!\")\n", " elif answer == \"right\" or answer == \"r\":\n", " print (\"Of course this is the Argument Room, I've told you that already!\")\n", " else:\n", " print (\"You didn't pick left or right! Try again.\")\n", " clinic()\n", "\n", "clinic()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "底下是六個比較的運算\n", "\n", "1.Equal to (==)\n", "\n", "2.Not equal to (!=)\n", "\n", "3.Less than (<)\n", " \n", "4.Less than or equal to (<=)\n", "\n", "5.Greater than (>)\n", "\n", "6.Greater than or equal to (>=)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "運算子先後順序請參考:\n", "http://www.swaroopch.com/notes/python/#op_exp ,\n", "但是建議適當使用括號讓程式方便閱讀同時避免錯誤" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Control Flow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "if-(elif)-else的架構可以參考底下這個例子" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-1\n", "0\n", "1\n" ] } ], "source": [ "def greater_less_equal_5(answer):\n", " if answer>5:\n", " return 1\n", " elif answer<5: \n", " return -1\n", " else:\n", " return 0\n", " \n", "print (greater_less_equal_5(4))\n", "print(greater_less_equal_5(5))\n", "print(greater_less_equal_5(6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### PygLatin" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "Pig Latin是個簡單的文字遊戲文字遊戲, 基本上是將一個字的字首移到字尾後再加上\"ay\". 程式需要考慮輸入的字是否有輸入(檢查字串長度len)是否是英文(isalpha). 在將自首移到字尾同時加上\"ay\"的過程中, 是簡單字串操作, 需注意的是字串第一個字元的編號是0, 同時若希望表示從第二個字元到字尾的指定方式除了[1:len(new_word)]外, 也可以用[1:]. 底下是一個有點變化的例子, 將字串輸入及操作過程定義為一函數pyglatin, 同時使用遞迴呼叫的技巧同時使用遞迴呼叫的技巧, 在沒有輸入正確文字時要求重新輸入" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a word:abcd\n", "abcd\n", "bcdaay\n" ] } ], "source": [ "pyg = 'ay'\n", "def pyglatin():\n", " original = input('Enter a word:') \n", " if len(original) > 0 and original.isalpha():\n", " print (original)\n", " word = original.lower()\n", " first = word[0]\n", " new_word = word+first+pyg\n", " new_word = new_word[1:]\n", " print (new_word)\n", " else:\n", " print ('empty')\n", " pyglatin()\n", "pyglatin()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# FUNCTIONS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "底下例子是定義一個計算平方的函數square, 定義的方式是使用def 開頭, 若有輸入參數, 則在括弧中放入參數, 若沒有輸入參數則括弧內是空的. 以縮排區別函數和主程式, 函數若有回傳值時 將回傳值寫在return後." ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 squared is 100.\n" ] }, { "data": { "text/plain": [ "100" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def square(n):\n", " \"\"\"Returns the square of a number.\"\"\"\n", " squared = n**2\n", " print (\"%d squared is %d.\" % (n, squared))\n", " return squared\n", " \n", "# Call the square function on line 9! Make sure to\n", "# include the number 10 between the parentheses.\n", "square(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Importing a module" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在python中欲使用特殊函式庫時需import特定模組, 以math module來說, 欲使用其中的sqrt函數時, 有幾種方法\n", "1. import math \n", "2. from math import sqrt\n", "3. from math import *\n", "\n", "底下是第一種方法, 使用時需以math.sqrt()呼叫. 另外這種方法會將math模組內其他物件也一起引入, 這可以用dir()函數看到math裡的函數 " ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n", "['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n" ] } ], "source": [ "import math\n", "print (math.sqrt(25))\n", "print (dir(math))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "第二種方法可以直接以sqrt()呼叫" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n" ] } ], "source": [ "from math import sqrt\n", "print (sqrt(25))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "第三種方式同樣也可以直接以sqrt()呼叫, 但是和第二種不一樣的地方在於前一種只有引入sqrt, 但是這一種方法將math模組全部引入全部引入, 程式撰寫過程中很容易混淆." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n" ] } ], "source": [ "from math import *\n", "print (sqrt(25))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LISTS & DICTIONARIES" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "python中的dictionary一個非常的架構,可以讓你方便的查詢資料,底下是一個簡單的dictionary" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "d = {'key1' : 1, 'key2' : 2, 'key3' : 3}\n", "print (d['key2'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "比方說,如果想要知道d裡面的key3對應的值為何,可以使用d['key3']查詢" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x = 5 , square_list = [25]\n", "x = 3 , square_list = [25, 9]\n", "x = 1 , square_list = [25, 9, 1]\n", "x = 2 , square_list = [25, 9, 1, 4]\n", "x = 4 , square_list = [25, 9, 1, 4, 16]\n", "[25, 9, 1, 4, 16]\n", "[1, 4, 9, 16, 25]\n" ] } ], "source": [ "start_list = [5, 3, 1, 2, 4]\n", "square_list = []\n", "\n", "# Your code here!\n", "\n", "for x in start_list:\n", " square_list.append(x**2)\n", " print (\"x = \",x,\", square_list = \",square_list)\n", "print (square_list)\n", "square_list.sort()\n", "print (square_list)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "number = 1 ; 2*number = 2\n", "number = 9 ; 2*number = 18\n", "number = 3 ; 2*number = 6\n", "number = 8 ; 2*number = 16\n", "number = 5 ; 2*number = 10\n", "number = 7 ; 2*number = 14\n" ] } ], "source": [ "my_list = [1,9,3,8,5,7]\n", "\n", "for number in my_list:\n", " # Your code here\n", " print (\"number =\",number,\"; 2*number =\",2*number)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "底下是一個簡單的迴圈,item 會依序由in之後的list取值,同時執行迴圈內部的程式,在這個例子中是逐一列出item" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n", "21\n" ] } ], "source": [ "for item in [1, 3, 21]: \n", " print (item)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "pear\n", "price: 3\n", "stock: 15\n", "orange\n", "price: 1.5\n", "stock: 32\n", "apple\n", "price: 2\n", "stock: 0\n", "banana\n", "price: 4\n", "stock: 6\n" ] } ], "source": [ "prices = {\"banana\": 4,\"apple\": 2,\"orange\": 1.5,\"pear\": 3}\n", "\n", "stock = {\"banana\": 6,\"apple\": 0,\"orange\":32,\"pear\": 15}\n", "\n", "for item in prices:\n", " print (item)\n", " print (\"price: %s\" % prices[item])\n", " print (\"stock: %s\" % stock[item])" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "def fizz_count(x):\n", " count = 0\n", " for item in x:\n", " if item == \"fizz\":\n", " count = count +1\n", " return count\n", " \n", "\n", "print (fizz_count([\"fizz\",\"cat\",\"fizz\"]))" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "banana\n", "price: 4\n", "stock: 6\n", "orange\n", "price: 1.5\n", "stock: 32\n", "apple\n", "price: 2\n", "stock: 0\n", "7.5\n" ] } ], "source": [ "shopping_list = [\"banana\", \"orange\", \"apple\"]\n", "\n", "stock = {\n", " \"banana\": 6,\n", " \"apple\": 0,\n", " \"orange\": 32,\n", " \"pear\": 15\n", "}\n", " \n", "prices = {\n", " \"banana\": 4,\n", " \"apple\": 2,\n", " \"orange\": 1.5,\n", " \"pear\": 3\n", "}\n", "\n", "# Write your code below!\n", "def compute_bill(food):\n", " total = 0\n", " for item in food:\n", " print (item)\n", " print (\"price: %s\" % prices[item])\n", " print (\"stock: %s\" % stock[item])\n", " total = total + prices[item]\n", " return total\n", "print (compute_bill(shopping_list))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Student Becomes the Teacher" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "底下是計算學生成績的一個程式,首先是學生的紀錄。每個學生的成績紀錄是以dictionary儲存,其中包含了\"name\",\"homework\",\"quizzes\",\"tests\"。注意dictionary中的值可以是list。" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [], "source": [ "lloyd = {\n", " \"name\": \"Lloyd\",\n", " \"homework\": [90.0, 97.0, 75.0, 92.0],\n", " \"quizzes\": [88.0, 40.0, 94.0],\n", " \"tests\": [75.0, 90.0]\n", "}\n", "alice = {\n", " \"name\": \"Alice\",\n", " \"homework\": [100.0, 92.0, 98.0, 100.0],\n", " \"quizzes\": [82.0, 83.0, 91.0],\n", " \"tests\": [89.0, 97.0]\n", "}\n", "tyler = {\n", " \"name\": \"Tyler\",\n", " \"homework\": [0.0, 87.0, 75.0, 22.0],\n", " \"quizzes\": [0.0, 75.0, 78.0],\n", " \"tests\": [100.0, 100.0]\n", "}" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "接著我們定義了幾個函數,首先是計算平均分數的函數average,他會把傳進來的一組(list)數字(numbers)加總(使用內建的sum函數),再將total除以資料個數(len)計算平均。注意為了避免資料型態出問題,我們使用float函數將total轉為浮點數" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Add your function below!\n", "def average(numbers):\n", " total = sum(numbers)\n", " #print total\n", " #print type(total)\n", " total = float(total)\n", " return total/len(numbers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "第二個函數是將傳進來的學生紀錄(dictionary),分別計算homework、 quizzes、 tests的平均,再計算加權和作為學生的平均分數" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def get_average(student):\n", " homework = average(student[\"homework\"])\n", " quizzes = average(student[\"quizzes\"])\n", " tests = average(student[\"tests\"])\n", "\n", " return homework*0.1+quizzes*0.3+tests*0.6\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "第三個函數是判斷成績(score)所對應的等第(letter grade)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def get_letter_grade(score):\n", " if score >= 90: \n", " return \"A\"\n", " elif score >= 80:\n", " return \"B\"\n", " elif score >= 70:\n", " return \"C\"\n", " elif score >= 60:\n", " return \"D\"\n", " else: \n", " return \"F\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "最後一個函數是計算整班(students-list)的平均分數,我們先建立一個空的results list,以方式,依序計算每個學生的平均分數,再加入results中,最後再計算平均。" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def get_class_average(students):\n", " results = []\n", " for student in students:\n", " results.append(get_average(student))\n", " return average(results)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "最底下的部份則是先建立一個班級的list,使用前面定義的函數計算平均成績" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "83.86666666666666\n", "B\n" ] } ], "source": [ " \n", "students = [lloyd, alice, tyler]\n", "class_avg = get_class_average(students)\n", "print (class_avg)\n", "print (get_letter_grade(class_avg))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [default]", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }