# Python learn note [TOC] ## Strings ### lower :::info 用於將字串全部轉為==小寫== ::: ```python= phrase = " Hello world " print(phrase.lower) Python> hello world ``` ### upper :::info 用於將字串全部轉為==大寫== ::: ```python= phrase = " Hello world " print(phrase.upper) Python> HELLO WORLD ``` ### isupper :::info 檢查字串中字母是否全為==大寫==,若全為大寫則回傳==True==,不是則回傳==False== ::: ```python= phrase = " Hello world " print(phrase.isupper) Python> False ``` ### islower :::info 檢查字串中字母是否全為==小寫==,若全為大寫則回傳==True==,不是則回傳==False== ::: ```python= phrase = " Hello world " print(phrase.islower) Python> False ``` ### index :::info 檢查字串中字元之==位置==(<font color=red> 從0開始計算,空白也計算在內,如有重複字母只會回傳第一個 </font>) ::: ```python= phrase = " Hello world " print(phrase.index("H")) Python> 1 ``` ### replace :::info ==替換==字串中的字元 ::: ```python= phrase = " Hello world " print(phrase.replace("H","h")) Python> hello world ``` ## Numbers :::success 數字可連續運算 ::: ### 基本運算 :::info 加減乘除(+、-、*、/) ::: ### 整數除法 :::info 雙斜線( ==//== ) ::: ```python= print(8//6) Python> 1 #小數點省略 ``` ### 取餘數 :::info 百分比符號(==%==) ::: ```python= numbers = 8 print(numbers % 5) Python> 3 #8/5=1...3 1 ``` ### str :::info 將==數字==型態轉為==字串==型態 ::: ```python= numbers = 8 print("印出數字為" + str(numbers)) Python> 印出數字為8 ``` ### abs :::info 將數字取絕對值 ::: ```python= numbers = -8 print(abs(numbers)) Python> 8 ``` ### pow :::info 取次方 ::: ```python= print(pow(2,4)) #x的y次方(x,y) Python> 16 ``` ### max,min :::info 取最大(小)值 ::: ```python= print(max(1,4,2323,44,535,100,88,43434)) Python> 43434 ``` ### round,ceil,floor :::info 四捨五入,無條件進位,無條件捨去 (後兩者需==import==) ::: ```python= from math import * num=123.578 #四捨五入 print(round(num)) #124 #無條件進位 print(ceil(num)) #124 #無條件捨去 print(floor(num)) #123 ``` ### sqrt :::info 開根號 ::: ```python= print(sqrt(64)) Python> 8.0 ``` ## List :::info 存放多種不同型態資料 ::: ### extend :::info 將列表做延伸 ::: ```python= scores = [90,70,40,42,23] friends = ["小黑","小白","小黃"] scores.extend(friends) print(scores) Python> [90, 70, 40, 42, 23, '小黑', '小白', '小黃'] ``` ### insert :::info 在列表中插入值 ::: ```python= scores = [90,70,40,42,23] scores.insert(2,30) #在第二位插入30 print(scores) Python> [90, 70, 30, 40, 42, 23] ``` ### remove :::info 在列表中==刪除==值 ::: ```python= scores = [90,70,40,42,23] scores.remove(90) print(scores) Python> [70, 30, 40, 42, 23] ``` ### clear :::info 清空列表 ::: ```python= scores = [90,70,40,42,23] scores.clear() print(scores) Python> [] ``` ### sort :::info 將列表由小到大排列 ::: ```python= scores = [90,70,40,42,23] scores.sort() print(scores) Python> [23, 40, 42, 70, 90] ``` ### reverse :::info 將列表==反轉== ::: ```python= scores = [90,70,40,42,23] scores.sort() print(scores) Python> [23, 42, 40, 70, 90] ``` ### 元組tuple :::info 與列表類似,使用小括號,但<font color=red>內容無法被新增刪除及修改</font> ::: ## Funciton ### 何為函式 :::info 函式是一段預先寫好的程式碼,幫助我們資料處理與運算,然後回傳給我們想要的資訊 ::: ### 函式的定義 :::info 使用def開頭,函式名稱只能為英文大小寫、數字及底線的組合 ::: ```python= def hello(): print("Hello world") hello() Python> Hello world ``` :::success 函式是可以傳入參數的 ::: ```python= def hello(name,age): print("Hello," + name + "\n你今年" + age + "歲") hello("Roger","22") Python> Hello,Roger 你今年22歲 ``` ### 回傳值return :::info 直接==結束==函式,回傳「資料」,方便繼續在外部運算 ::: ```python= def add(num1,num2): print(num1 + num2) return 10 value = add(3,4) print(value) Python> 7 10 ``` :::success 如果函式中沒有return值,就會回傳==None== ::: ```python= def add(num1,num2): print(num1 + num2) value = add(3,4) print(value) Python> 7 None ``` ## IF判斷句 ### 單純if判斷句 ```python= hungry = True if hungry: print("go to eat") Python> go to eat ``` ### if ...else ```python= rainy = False if rainy: print("drive to work") else: print("walk to work") Python> walk to work ``` ### if...elif :::success 一個等號為賦值,兩個等號為比較 ::: ```python= point = 100 if point == 100: print("got 1000") elif point >= 80: print("got 500") elif point >= 60: print("got 100") else: print("give me 300") Python> got 1000 ``` ### if不相等 :::info 使用 != 或 not() ::: ### if判斷句練習 #### 實作max函式 ```python= def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 elif num3 >= num1 and num3 >= num2: return num3 print(max_num(1, 4, 5)) Python> 5 ``` #### 實作簡易計算機 ```python= def cal(): num1 = float(input("type first number:")) op = input("type opration way:") num2 = float(input("type second number:")) if op == "+": print(num1+num2) elif op == "-": print(num1-num2) elif op == "*": print(num1*num2) elif op == "/": print(num1/num2) else: print("type error please retry!") cal() ``` ## Dictionary :::info 許多鍵與值的搭配,使用大括號 ::: ```python= dic = {"蘋果":"apple", "香蕉":"banana", "貓":"cat", "狗":"dog"} print(dic["蘋果"]) ``` ## while迴圈應用:實作猜數字遊戲 :::info 設置一謎底讓用戶猜答案,但最多只能猜三次,輸入的數字太大或太小都有提示 ::: ```python= print("welcome to the game") secret_num = 99 guess = None guess_limit = 1 while guess_limit <= 3 and guess != secret_num: guess_limit += 1 guess = int(input("type a number: ")) if guess > secret_num: print("smaller") elif guess < secret_num: print("bigger") if guess == secret_num: print("congratulation!") else: print("YOU LOSS~") ``` ## for迴圈 :::info for 變數 in 字串或列表 要重複執行的程式碼 ::: ### 實作pow函數 ```python= def power(base_num, pow_num): result = 1 for index in range(pow_num): result = result * base_num return result print(power(2,3)) Python> 8 ``` ## 二維陣列及巢狀迴圈 :::info 當列表中包含第二個以上的列表時,就稱為二維陣列 ::: ```python= num = [ [0,1,2], [3,4,5], [6,7,8], [9] ] ``` :::info 二維陣列取值方法 ::: ```python= print(num[行][列]) ``` :::info 當迴圈內包含第二個以上迴圈時,就稱為巢狀迴圈 ::: ### 利用巢狀迴圈在二維陣列取值 ```python= for row in num: for col in row: print(col) Python> 0 1 2 3 4 5 6 7 8 9 ``` ## 檔案的讀取與寫入 :::info open("檔案路徑",mode="開啟模式") ::: :::success 檔案路徑分為==絕對路徑==與==相對路徑== ::: ### 讀取 ```python= file = open("123.txt", mode="r") print(file.read()) file.close() ``` ### 寫入 ```python= with open("123.txt", mode="a", encoding="utf-8") as file: file.write("\n你好啊") ``` ## 實作一問答程式 ```python= from question import Question test = [ "1. 1+3=?\n(a) 2\n(b) 3\n(c) 4\n\n", "2. 一公尺等於幾公分?\n(a) 10\n(b) 100\n(c) 1000\n\n", "3. 香蕉是什麼顏色?\n(a) 黑色\n(b) 黃色\n(c) 白色\n\n" ] questions = [ Question(test[0], "c"), Question(test[1], "b"), Question(test[2], "b"), ] def run_test(questions): score = 0 for question in questions: answer = input(str(question.decription) + "Answer:") if answer == question.answer: score += 1 print("You got " + str(score) + " point, in " + str(len(questions)) + " questions") run_test(questions) ``` :::success class Question ::: ```python= class Question: def __init__(self,description,answer) : self.decription = description self.answer = answer ```