2019年12月10日 星期二

python.ipynb

{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python程式語言"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python變數在使用前一定記得先指定初值,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grade = 76\n",
    "height = 175.5\n",
    "weight = 75.5\n",
    "\n",
    "print(\"成績 = \" + str(grade))\n",
    "print(\"身高 = \" + str(height))\n",
    "print(\"體重 = \" + str(weight))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python變數可以指定成整數值,和執行相關運算如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 5\n",
    "print(type(x)) # 顯示 \"<class 'int'>\"\n",
    "print(x)       # 顯示 \"5\"\n",
    "print(x + 1)   # 加法: 顯示 \"6\"\n",
    "print(x - 1)   # 減法: 顯示 \"4\"\n",
    "print(x * 2)   # 乘法: 顯示 \"10\"\n",
    "print(x / 2)   # 除法: 顯示 \"2.5\"\n",
    "print(x // 2)  # 整數除法: 顯示 \"2\"\n",
    "print(x % 2)   # 餘數: 顯示 \"1\"\n",
    "print(x ** 2)  # 指數: 顯示 \"25\"\n",
    "x += 1\n",
    "print(x)  # 顯示 \"6\"\n",
    "x *= 2\n",
    "print(x)  # 顯示 \"12\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python變數可以指定成浮點數值,和執行相關運算,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y = 2.5\n",
    "print(type(y)) # 顯示 \"<class 'float'>\"\n",
    "print(y, y + 1, y * 2, y ** 2) # 顯示 \"2.5 3.5 5.0 6.25\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python語言的布林(Boolean)資料型態可以使用True和False關鍵字來表示"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = True\n",
    "y = False\n",
    "\n",
    "print(x)\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "當在Python程式建立字串後,我們就可以顯示字串、計算字串長度、連接2個字串告格式化顯示字串內容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "str1 = 'hello'     # 使用單引號建立字串\n",
    "str2 = \"python\"    # 使用雙引號建立字串\n",
    "print(str1)        # 顯示 \"hello\"\n",
    "print(len(str1))   # 字串長度: 顯示 \"5\"\n",
    "str3 = str1 + ' ' + str2  # 字串連接\n",
    "print(str3)        # 顯示 \"hello python\"\n",
    "str4 = '%s %s %d' % (str1, str2, 12)  # 格式化字串\n",
    "print(str4)        # 顯示 \"hello python 12\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python字串物件提供一些好用的方法來處理字串,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"hello\"\n",
    "print(s.capitalize())  # 第1個字元大寫: 顯示 \"Hello\"\n",
    "print(s.upper())       # 轉成大寫: 顯示 \"HELLO\"\n",
    "print(s.rjust(7))      # 右邊填空白字元: 顯示 \"  hello\"\n",
    "print(s.center(7))     # 置中顯示: 顯示 \" hello \"\n",
    "print(s.replace('l', 'L'))  # 取代字串: 顯示 \"heLLo\"\n",
    "print('  python '.strip())  # 刪除空白字元: 顯示 \"python\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 練習"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "請設定兩個變數name, id, class為自己的姓名、學號與班級,並且進行輸出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "將華氏溫度轉換為攝氏溫度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f =  input ( '請輸入華氏溫度: ' )\n",
    "c = \n",
    "print ( ' %.1f華氏度= %.1f攝氏度'  % (f, c))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "輸入半徑計算圓的周長和面積"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "radius =  float ( input ( '請輸入圓的半徑: ' ))\n",
    "perimeter =  2  * math.pi * radius\n",
    "area = math.pi * radius * radius\n",
    "print ( '周長: %.2f '  perimeter)\n",
    "print ( '面積: %.2f '  area)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 條件控制 – if單選條件敘述\n",
    "判斷氣溫決定是否加件外套的if條件敘述,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t = int(input(\"請輸入氣溫 => \"))\n",
    "if t < 20:\n",
    "    print(\"加件外套!\")\n",
    "print(\"今天氣溫 = \" + str(t))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "學生成績以60分區分是否及格的if/else條件敘述"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = int(input(\"請輸入成績 => \"))\n",
    "if s >= 60:\n",
    "    print(\"成績及格!\")\n",
    "else:\n",
    "    print(\"成績不及格!\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python多選一條件敘述是if/else條件的擴充,在之中新增elif關鍵字來新增一個條件判斷,就可以建立多選一條件敘述,在輸入時,別忘了輸入在條件運算式和else之後的「:」冒號。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "輸入年齡值來判斷不同範圍的年齡,小於13歲是兒童;小於20歲是青少年;大於等於20歲是成年人,因為條件不只一個,所以需要使用多選一條件敘述"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = int(input(\"請輸入年齡 => \"))\n",
    "if a < 13:\n",
    "    print(\"兒童\")\n",
    "elif a < 20:\n",
    "    print(\"青少年\")\n",
    "else:\n",
    "    print(\"成年人\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python語言並不支援「條件運算式」(Conditional Expressions),我們可以使用單行if/else條件敘述來代替,其語法如下所示:\n",
    "    變數 = 變數1 if 條件運算式 else 變數2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "12/24制的時間轉換運算式如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "h = h-12 if h >= 12 else h"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 練習"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "成績轉換為等級"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score = input ( '請輸入成績: ' )\n",
    "if score >=  90\n",
    "    grade =  ' A '\n",
    "else if score >=  80\n",
    "    grade =  ' B '\n",
    "else if score >=  70\n",
    "    grade =  ' C '\n",
    "else if score >=  60 \n",
    "    grade =  ' D '\n",
    "else\n",
    "    grade =  ' E '\n",
    "print ( '對應的等級是: ' , grade)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 迴圈控制 – for計數迴圈"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在for迴圈的程式敘述中擁有計數器變數,計數器可以每次增加或減少一個值,直到迴圈結束條件成立為止。\n",
    "\n",
    "基本上,如果已經知道需重複執行幾次,就可以使用for計數迴圈來重複執行程式區塊。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在輸入最大值後,可以計算出1加至最大值的總和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = int(input(\"請輸入最大值 =>\"))\n",
    "s = 0\n",
    "for i in range(1, m + 1):\n",
    "    s = s + i\n",
    "print(\"總和 = \" + str(s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "range(101)可以產生一個0到100的整數序列。\n",
    "\n",
    "range(1, 100)可以產生一個1到99的整數序列。\n",
    "\n",
    "range(1, 100, 2)可以產生一個1到99的奇數序列,其中2是步長,即數值序列的增量。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# while條件迴圈"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "while迴圈敘述需要在程式區塊自行處理計數器變數的增減,迴圈是在程式區塊開頭檢查條件,條件成立才允許進入迴圈執行。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用while迴圈來計算階層函數值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = int(input(\"請輸入階層數 =>\"))\n",
    "r = 1\n",
    "n = 1\n",
    "while n <= m:\n",
    "    r = r * n\n",
    "    n = n + 1\n",
    "print(\"階層值! = \" + str(r))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 練習"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "猜數字遊戲"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "answer = random.randint( 1 , 100 )\n",
    "counter =  0 \n",
    "while  True\n",
    "    counter +=  1 \n",
    "    number =  int ( input ( '請輸入: ' ))\n",
    "    if number < answer\n",
    "         print ( '大一點' )\n",
    "    elif number > answer\n",
    "         print ( '小一點' )\n",
    "    else \n",
    "         print ( '恭喜你猜對了! ' )\n",
    "    break\n",
    "print ( '你總共猜了%d次'  %counter)\n",
    "if counter >  7\n",
    "    print ( '你的智商餘額明顯不足' )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "輸入一個正整數判斷它是不是質數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import sqrt\n",
    "\n",
    "num =  int ( input ( '請輸入一個正整數: ' ))\n",
    "end =  int (sqrt(num))\n",
    "is_prime =  True \n",
    "for x range ( 2 , end)\n",
    "     if num % x =  0 :\n",
    "        is_prime =  False \n",
    "        break \n",
    "if is_prime and num !=  1 :\n",
    "     print ( ' %d是質數'  % num)\n",
    "else :\n",
    "     print ( ' %d不是質數'  % num)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函數 – 定義函數"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在Python程式建立沒有參數列和傳回值的print_msg()函數,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def print_msg():\n",
    "    print(\"歡迎學習Python程式設計!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上述函數名稱是print_msg,在名稱後的括號定義傳入的參數列,如果函數沒有參數,就是空括號,在空括號後不要忘了輸入「:」冒號。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python函數如果有傳回值,我們需要使用return關鍵字來傳回值。\n",
    "\n",
    "例如:判斷參數值是否在指定範圍的is_valid_num()函數,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_valid_num(no):\n",
    "    if no >= 0 and no <= 200.0:\n",
    "        return True\n",
    "    else:\n",
    "        return False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再來是一個執行運算的convert_to_f()函數,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_to_f(c):\n",
    "    f = (9.0 * c) / 5.0 + 32.0\n",
    "    return f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函數 – 函數呼叫"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python程式碼呼叫函數是使用函數名稱加上括號中的引數列。因為print_msg()函數沒有傳回值和參數列,呼叫函數只需使用函數名稱加上空括號,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print_msg()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "函數如果擁有傳回值,在呼叫時可以使用指定敘述來取得傳回值,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = convert_to_f(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果函數傳回值為True或False,例如:is_valid_num()函數,我們可以在if條件敘述呼叫函數作為判斷條件,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if is_valid_num(c):\n",
    "    print(\"合法!\")\n",
    "else:\n",
    "    print(\"不合法\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 練習"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "實作判斷一個數是不是質數的函數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def  is_prime ( num ):\n",
    "    for factor in  range ( 2 , num):\n",
    "         if num % factor ==  0 :\n",
    "             return  False \n",
    "    return "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 清單"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python語言的「清單」(Lists)類似其他程式語言「陣列」(Arrays),中文譯名有清單、串列和列表等。\n",
    "\n",
    "不同於字串型態的不能更改,清單允許更改(Mutable)內容,我們可以新增、刪除、插入和更改清單的項目(Items)。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python清單(Lists)是使用「[]」方括號括起的多個項目,每一個項目使用「,」逗號分隔,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ls = [6, 4, 5]    # 建立清單\n",
    "print(ls, ls[2])  # 顯示 \"[6, 4, 5] 5\"\n",
    "print(ls[-1])     # 負索引從最後開始: 顯示 \"5\"\n",
    "ls[2] = \"py\"      # 指定字串型態的項目\n",
    "print(ls)         # 顯示 \"[6, 4, 'py']\"\n",
    "ls.append(\"bar\")  # 新增項目\n",
    "print(ls)         # 顯示 \"[6, 4, 'py', 'bar']\"\n",
    "ele = ls.pop()    # 取出最後項目\n",
    "print(ele, ls)    # 顯示 \"bar [6, 4, 'py']\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python清單可以在「[]」方括號中使用「:」符號的語法,即指定開始和結束來分割清單成為子清單,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nums = list(range(5))  # 建立一序列的整數清單\n",
    "print(nums)            # 顯示 \"[0, 1, 2, 3, 4]\"\n",
    "print(nums[2:4])       # 切割索引2~4(不含4): 顯示 \"[2, 3]\"\n",
    "print(nums[2:])        # 切割索引從2至最後: 顯示 \"[2, 3, 4]\"\n",
    "print(nums[:2])        # 切割從開始至索引2(不含2): 顯示 \"[0, 1]\"\n",
    "print(nums[:])         # 切割整個清單: 顯示 \"[0, 1, 2, 3, 4]\"\n",
    "print(nums[:-1])       # 使用負索引切割: 顯示 \"[0, 1, 2, 3]\"\n",
    "nums[2:4] = [7, 8]     # 使用切割來指定子清單\n",
    "print(nums)            # 顯示 \"[0, 1, 7, 8, 4]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 清單 – 走訪清單"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python程式是使用for迴圈走訪顯示清單的每一個項目,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "animals = ['cat', 'dog', 'bat']\n",
    "for animal in animals:\n",
    "    print(animal)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上述for迴圈可以一一取出清單每一個項目和顯示出來,如果需要顯示清單各項目的索引值,我們需要使用enumerate()函數,如下所示:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for index, animal in enumerate(animals):\n",
    "    print(index, animal)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}

沒有留言:

張貼留言