# Python 基本應用 ## 1. 基本資料型態 & 變數 ```python= from math import * # 將數字的函式庫引入 # 基本資料型態 & 變數 # 清除終端機指令 Windows cls Mac clear # 字串 name = "鳳皇" test = "Hello" # 數字 age = 27 # 布林值 is_male = True # 變數名稱只能是英文or數字or _ 的組合 # 變數開頭不可以是數字 print("我是" + name ) print("爬蟲學習") print("我是男的") # 字串使用用法 print("Hello \n你好嗎?") print("Hello\' 你好嗎?") # 函式 function # 先寫好的程式 調用後執行 # test.lower() , test.upper() # 功能為轉成小寫 回傳 , 轉成大寫 # test.isupper()test.islower() 會回傳True or False # 判斷字串內容是否都為大寫 # 函式可以進行疊加 # 下為範例 print(test.lower().islower()) # 即可變全小寫後回傳True # 中括號[] 在字串後面加上[數字] # 例如 test[2] 會回傳字串當中數字所代表的位置 s # test.index("H") 這個函式可以找 當中的值在哪個位址 # test.replace("H","A") 這個函數用來替換 將H替換成A # 數字的用法 # str(age) 將數字轉換成字串 # abs(age) 取絕對值 # pow(2,4) 次方 例取2的四次方 # max(2,3,55,87) 取當中最大的數字回傳 # min() 相反 # round(4.4) 取四捨五入 = 4 # floor(4.6) 無條件捨去 = 4 # ceil(4.3) 無條件進位 = 5 # sqrt(64) 開根號 = 8 ``` ## ps.基本計算機建立 ```python= from math import * # 基本計算機建立 nmber1 = input("請輸入第一個數字: ") nmber2 = input("請輸入第二個數字: ") # 將輸入的資料 存到 nmber1,nmber2 變數 # 將字串轉成數字 int(nmber1) 用float 轉成浮點數 print( int(nmber1) + int(nmber2) ) ``` ## 2. 列表用法 ```python= # 列表用法 friends = ["小白","小黑","小黃"] print(friends[1]) # 取得 列表當中第幾位 # friends[0:2] 取從第一位之前 第三位之後 # friends[0:] 後面不接數字 為取到結束 friends[0] = "小藍" # 將第一位改成小藍 scores =[90,30,40,50] # scores.extend(friends) 將列表相接 # scores.append(87) 將列表最後再加上一個值 # scores.insert(2,60) 在第三位插上 60 這個值 # scores.remove(90) 將列表中的 90 刪除 # scores.clear() 將列表全部清空 # scores.pop() 移除列表最後一位 # scores.sort() 將列表由小到大做排列 # scores.reverse() 將列表做反轉讀取 # scores.index(40) 輸入想找的值會回饋我們的位置 # scores.count(50) 列表當中有幾個 50 , 1 ``` ## 3. 元組 tuple ```pytho= # 元組 tuple scores = (50,60,55,43,87) # len(scores) 當中有多少值 # 可用與列表當中相同函式 # 元組和列表差別為 不可新增 修改 刪除 ``` ## 4. 函式 function ```python= # 函式 function def hello(name,age): print("hello "+ name + "你今年" + str(age) + "歲") # hello("鳳皇",27) def add(namber1,namber2): print( namber1 + namber2 ) return 30 vaule = add(3,53) print(vaule) # 程式回由下往上執行 # 且如果沒有return 會預設 return None # 最終接收為 57 , 30 ``` ## 5. if 判斷句 ```python= # if 判斷句 # 1. # 如果 我肚子餓 if # 我就去吃飯 hungry = True if hungry: print("我就去吃飯") # 2. # 如果 今天下雨 if # 我就開車去上班 # 否則 else # 我就走路去上班 Rainy = True if Rainy: print("我就開車去上班") else: print("我就走路上班") # 3. # 如果 你考100分 == # 我就給你1000塊 # 或是如果 你考80分以上 >= # 我就給你500塊 # 或是如果 你考60分以上 >= # 我就給你100塊 # 否則 # 你就給我300塊 score = 100 if score == 100: print("我給你1000塊") elif score >= 80: print("我給你500塊") elif score >= 60: print("我給你100塊") else: print("你給我300塊") # 4. # 如果 你考一百分 且今天下雨 and # 我給你1000 # 否則 # 你給我100 score = 90 Rainy = True if score == 100 and Rainy: print("我給你1000") else: print("你給我100") # 5. # 如果 你考一百分 或今天下雨 or # 我給你1000 # 否則 # 你給我100 score = 90 Rainy = True if score == 100 or Rainy: print("我給你1000") else: print("你給我100") # 6. # 如果 你考一百分 或沒有下雨 not() # 我給你1000 # 否則 # 你給我100 score = 90 Rainy = True if score == 100 or not(Rainy): print("我給你1000") else: print("你給我100") ``` ## ps.2 進階計算機 ```python= # 進階計算機 num1 = float(input("請輸入第一個數: ")) op = input("請輸入運算符號: ") num2 = float(input("請輸入第一個數: ")) if op == "+": print(num1+num2) elif op == "-": print(num1-num2) elif op == "*": print(num1*num2) elif op == "/": print(num1/num2) else: Print("不支援的運算符號") ``` ## 6. 字典 dictionary ```python= # 字典 dictionary # key value # 鍵 值 dic = {"蘋果":"apple" , "香蕉":"banana" , "貓":"cat" , "狗":"dog"} print(dic["蘋果"]) ``` ## 7. while 迴圈 ```python= # while 迴圈 i = 1 while i <= 5: print(i) i += 1 print("迴圈結束") ``` ## ps.3 猜數字遊戲 ```python= # 猜數字遊戲 secret_num = 99 guess = None guess_count = 0 guess_limit = 3 out_of_limit = False while secret_num != guess and not(out_of_limit): guess_count += 1 if guess_count <= guess_limit: guess = int(input("請輸入數字: ")) if guess > secret_num: print("在小一點") elif guess < secret_num: print("在大一點") else: out_of_limit = True if out_of_limit: print("失敗") else: print("恭喜獲勝") ``` ## 8. for 迴圈 ```python= # for 迴圈 # for 變數 in 字串or列表: # 要重複執行的程式碼 # for letter in "你好": # print(letter) # for num in [0,1,2,3,4]: # print(num) # range(5) 只跑範圍內 0-4 # range(2,7) 跑2-7 # for num in range(5): # print(num) # 練習 次方 pow(2,6) # 將 base_num 放進result # index 迴圈 pow_num-1的次數 # 最後相乘 在回傳給result def power(base_num,pow_num): result = base_num for index in range(pow_num-1): result = result * base_num return result print(power(2,6)) ``` ## 9. 2維列表 , 巢狀迴圈 ```python= # 2維列表 , 巢狀迴圈 # row = 行 , column = 列 nums = [ [0,1,2] , [3,4,5] , [7,8,9] ] # print(nums[0][1]) #巢狀迴圈 for row in nums: for col in row: print(col) ``` ## 10. 檔案的讀取與寫入 ```python= # 檔案的讀取與寫入 # open("檔案路徑" , mode="開啟模式") # 絕對路徑 ex: c:/User/hibyby/Desktop/python/123.txt # 相對路徑 以程式的位置做延伸 ex: 123.txt #要記得關閉file.close() # mode = "r" 讀取 # mode = "w" 覆寫 # mode = "a" 在原先的資料後寫東西 # file.readline() 讀取一行 # for 迴圈將每行讀出 # file = open("123.txt", mode="r") # for line in file: # print(line) # # print(file.read()) # file.close() # 將每一行放入列表 # file = open("123.txt", mode="r") # print(file.readlines()) # file.close() # 進行複寫 mode = "w" file = open("123.txt", mode="w") # print(file.readlines()) file.write("hello") file.close() # 在原先資料後寫東西 # 要進行編碼才能寫中文 # file = open("123.txt", mode="a" , encoding="utf-8") # print(file.readlines()) # file.write("\n你好") # file.close() # 不用每次都進行關閉 # 出了with 迴圈後會自行關閉 with open("123.txt", mode="a" , encoding="utf-8") as file: file.write("\n掰掰") ``` ## 11. 模組的使用 ```python= # 模組的使用 # pip 套件管理工具 # 模組可使用變數,函式 # 且有內建模組 # python module list 做尋找 # sys.path 內建模組放置地方 # 可在import 後加上 as 變更模組名方便引用 # import tool as tol import tool import token import sys # print(tool.max_num(3,77,5)) print(sys.path) ``` ## ps.4 問答程式 ```python= # 問答程式 # from question import Question 只引入 Question 這個class # 不會引入變數 from question import Question test = [ "1+3=?\n(a) 2\n(b) 3\n(c) 4\n\n", "1公尺=幾公分?\n(a) 10\n(b) 100\n(c) 1000\n\n", "香蕉是什麼顏色=?\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(question.discription) if answer == question.answer: score += 1 print("你得到" + str(score) + "分,共" + str(len(questions))+ "題") run_test(questions) ``` 附屬程式 ```python= # 定義一個資料型態 Question class Question: def __init__(self , discription , answer): self.discription = discription self.answer = answer ``` ## 12. 類別class,物件object ```python= # 類別class,物件object # 傳入第一個參數為self , 後面為資料型態所要的資訊 self為物件本身 # 以Phone 為例 需要os,numbermis_waterproof 這些為物件所需屬性 # Class 為模板 讓我們知道要創建手機需要的資訊 class Phone: def __init__(self , os , number , is_waterproof): self.os = os self.number = number self.is_waterproof = is_waterproof # 寫個函式判斷手機系統是否為IOS def is_ios(self): if self.is_ios == "ios": return True else: return False # 函式中 使用相加 def add (self,number1,number2): return number1 + number2 # 創建一個物件 Phone1 他是 IOS 屬性 , 號碼是 1234 屬性 , 防水性是 True 屬性 phone1 = Phone("ios",1234,True) print(phone1.number) phone2 = Phone("andriod",90,False) print(phone2.os) # 如何使用判斷IOS print(phone1.is_ios()) print(phone1.add(5,6)) ``` ## 13. inheritance 繼承 ```python= from student import Student student1 = Student("鳳凰",27,"高中") student1.print_school() ``` 人 ```python= # class 為人 資料中有 name,age 且帶有兩個函數為印出年紀和姓名 class Person: def __init__(self,name,age): self.name = name self.age = age def print_name(self): print(self.name) def print_age(self): print(self.age) ``` 學生 繼承 人 ```python= # class 為學生 資料中有 name,age,school 且帶有兩個函數為印出年紀和姓名,學校 # 這時候可以繼承人的類別 Student()加入person # 相當於將 Person 類別複製到最上方 # 相同部分可以刪除 from person import Person class Student(Person): def __init__(self,name,age,school): self.name = name self.age = age self.school = school # def print_name(self): # print(self.name) # def pring_age(self): # print(self.age) def print_school(self): print(self.school) ``` ## ps.5 小範例 找零 ```python= def find_change(amount): # 初始化可用的鈔票和零錢面額 denominations = [500, 100, 50, 10, 5, 1] # 計算找零金額 change = 1000 - amount # 初始化一個列表,用於存儲每種面額的數量 change_counts = [0] * len(denominations) # 遍歷每種面額,計算每種面額的數量 for i in range(len(denominations)): while change >= denominations[i]: change -= denominations[i] change_counts[i] += 1 # 輸出找零方式 for i in range(len(denominations)): print(denominations[i], end="元: ") # 印出面額 print(change_counts[i], end=" ,") # 印出對應的數量 # 讀入客人的消費金額 amount = int(input()) # 調用函數計算找零方式並輸出 find_change(amount) ```