Skip to main content

Intro_Python_101

hackmd-github-sync-badge

Open In Colab

01.Python_basic基礎

  • 我們先來認識所謂「程式」的基礎吧
    • 建立環境
  • 程式的組成
    - 基本資料型態 (整數、浮點數、字串、布林)(串列、元組、字典、集合)
    - 格式化的輸出與輸入(print, input())
    - 運算子、運算式與敘述(+-*/、大小等於)
    - 選擇性敘述(if-else)
    - 迴圈(for, while)
    - 函數(def foo():)
    - 類別(class Foo():)
import this

建立Python環境

以下方法擇一皆可

  • 官網下載Python: https://www.python.org/

    • 電腦直接裝Python者,可用命令列或IDEL
  • 開啟Google的Colab

    • 線上開啟新的筆記本,也等於跟google要了一個虛擬機
    • 如果你要自學,推薦使用Colab
  • 安裝ANACONDA:

    • 安裝ANACONDA者,可用jupyter notebook,初學者建議
    • 如果你要自學,本文推薦下載,但比較大包
!nvidia-smi

0.Python的變數

  • 變數,儲存內容的盒子
  • 在Python,變數更像是貼標籤的概念(標籤指向的資料改變,)
a = 1
a
#我有a隻手機
print("我有",a,"隻手機")

1.立馬進行基本計算

加減乘除非常方便,直接進行即可

1+1
# **是次方

print(2**10)
# 除法OK的

99/44
#餘數%

dise = 9487 % 6 #012345 骰子

print(dise+1)

2.輕鬆上手資料型態

基本資料型態在python指的是整數int、浮點數float(就是小數)、字串str(文字)、布林bool(True or False)

想知道手上資料的型態,可以用type()來確認

b=True
b
# type()
type(b)
num1 = 78
num2 = 0.55

type(num1), type(num2)
1+2
1+2.
type(1+2.)
type(87), type(55.66),  type("5566"), type( 1 != 1 )
'我有一串"文字"'

Question1

  • 要怎麼確認是文字、整數還是小數?
#文字的數字怎麼確認?
type('88')

Question2

  • 如何強制將小數轉成整數?
#浮點數轉整數

int(100.666)

3.快速使用輸入與輸出

  • 輸出以print()把資料印出來

  • 輸入就以input()讓使用者使用

  • 在jupyter notebook,每個cell最後一個print()可以省略

input()
input('請輸入姓名:')
'我的名子是:'+input()
print('我的名子是:'+input())
name = input()
print('我的名子是:' + name)
email = input( '我的email帳號:')
print('我的email帳號:',email)
顏文字 = "(゚Д゚)< ============O))"

顏文字
顏文字*500

print()

print("hi")
#3種寫法一次比較
name = "野原新之助"
age = 5

print(f"大姊姊我是{name},我今年{age}歲!!") # f-string

print("大姊姊我是%s,我今年%d歲!!"% (name, age))
print("大姊姊我是{},我今年{}歲!".format(name, age))

4.第一個動手做:計算BMI

  • 運用前述所學,設計一個BMI計算器,能夠正確計算BMI
  • BMI = 體重(公斤) / 身高平方(平方公尺)
  • 由使用者輸入體重、身高,顯示計算結果
# 來練習吧


5.條件判斷

3>=2
"Z" > "b" #利大於弊
a=5
b=1

if a == b:
print("a==b")
elif a > b:
print('a>b')
else:
print("a<b")

if (1):
print('成立')
else:
print('不成立') # None, False, 0
if 3<2:
print("Yse")
else:
print("NO")
if 1!=1:
print("YES")
else:
print("NO")

6.必須知道什麼是串列list

# list

[ 1, 2, 3.14, 7.788, "c8763"]
[7,5,4.444,"挖苦挖苦",True,False]
APPLE = [1, 2, 3, 0]
PEN = [7, 7, 3, 2]
APPLE + PEN
APPLE-PEN
APPLE*5

切片

#APPLE[ 頭0 : 尾前 ]
APPLE=[9, 5, 2, 7]
APPLE[2]
#APPLE[ 魚頭: 魚屁股]
APPLE[0:2]
APPLE[0 : 3]
APPLE[ :3]  #不包含第4
APPLE[-1]
!pip install twstock
import twstock

stock= twstock.Stock("2330")
stock.price[-1]
= "庭院深深深幾許"
[0]
[2:5]
[-5:]
list()

7.第二個動手做:線上遊戲命名產生器

80%玩家表示,最花時間的就是命名,既然我們學會了串列list,那我們來嘗試做一個命名產生器

首先以list把地點跟明星名字存起來

local = ["基隆",'南港','松山','台北','萬華','板橋','樹林','鶯歌','桃園','中壢','楊梅','竹北','新竹','苗栗','銅鑼',
'后里','豐原','潭子','太原','台中','大慶','烏日','新烏日','成功','彰化','花壇','大村','員林','永靖','社頭',
'田中','二水','林內','民雄','嘉義','林鳳營','高雄']
star = ['山下智囧','囧把刀','尾田賀一航','木村倒頭哉','湯姆嗑吐司','木村唾液','今晨五','彭于晏','朝偉哥',"山道猴子"]
local[2]+star[1]
import random

a = random.sample(local,1)+ random.sample(star,1) #shift+tab
"".join(a)

用亂數取出一組組合,加在一起組成新的list,最後在取出list內容將字串合在一起

不命名變數也可以,方法百百種,python很自由

"".join(random.sample(local, 1) + random.sample(star, 1))

8.kv配對的字典

{"ip":"0.0.0.0"}
成績 =  {"數學" : [100,90,80] }
同學 = {
"andy":[183,70],
"Alice":[163,45]
}
同學
同學["andy"][1]

9.條件判斷II:如果,否則

可以分成

  • if: #條件成立執行以下描述
  • if else #如果(成立就執行...),否則(成立就執行...)
  • if elif else #如果(成立就執行...),否則如果(成立就執行...),否則(成立就執行...)
A = 5
B = 8
if A == B:
print('A = B')
if A != B:
print("a!=b")
if A == B:
print('A == B')
else:
print('A != B')
if A > B:
print('A > B')
elif A < B:
print('A < B')
else:
print('A == B')

現學現賣之「智慧聊天機器人」

say = input(">>")
if say == '早安':
print("早安唷")
else:
print("你說"+say+"阿? 阿阿阿阿阿我知道了")

10.人生就是迴圈

迴圈是程式語言的特徵,讓電腦協助你重覆執行某項判斷,主流用法就是for迴圈與while迴圈,另外python還有一個枚舉可以使用。

10-1 For迴圈

  • 先來個for迴圈吧,基本上for迴圈常與list結合使用
for 指標 in 要判別的資料集:
執行項目
五俗蘭 = ["紅茶", "綠茶", "烏龍", "鐵觀音", "多多冰沙", "八冰綠", "抹茶拿鐵"]
print(五俗蘭)
五俗蘭[:4]
for i in 五俗蘭:
print(i)
for i in range(5):
print(五俗蘭[i])
len(五俗蘭)
for i in range(7):
print(五俗蘭[i])
for i in range(len(五俗蘭)):
print(五俗蘭[i])
for i in 五俗蘭:
print(i)
# 如果list超級大,可以用iter + next節省記憶體
五俗蘭_iterator = iter(五俗蘭)

while True:
try:
i = next(五俗蘭_iterator)
print(i)
except StopIteration:
break

10-2 enumerate()枚舉

假設我們要迭代list成員的名稱,並獲取list中每個成員的位置。可以用enumerate,又稱枚舉

for i, v in enumerate(五俗蘭):
print(i, v)

10-3 while迴圈

while迴圈,除非成立才會跳出循環

初始值
while 條件式:
   程式區塊
(索引變化)
count = 0

while (count < 6):
print('The count is:', count)
count += 1 #count =count+1

print ("Good bye!")
# continue用法

i = 1
while (i < 6):
i += 1 # i=i+1
if i%2 > 0: #1
continue
print(i)
# break用法
i = 1
while (1):
print(i)
i += 1
if i > 10:
break

*現學現賣之「金庫密碼」

password = '' #先設一個空字串讓程式知道

while password != "1234":
password = input("快點輸入密碼>>")

if password == '1234':
print("密碼正確")
break
else:
print("密碼錯誤再來一次")

11.函數其實很精彩

用來打包你所會的一切,必要時呼叫出來就可以用

def foo(引數1,引數2):
執行內容
retuen 回傳值

呼叫時使用

foo(引數1,引數2)
def toto_bmi(wei, hei):
bmi = float(wei) / float(hei)**2
return bmi
a = toto_bmi(70, 1.73)
a
#BMI=w/h**2

def cal_BMI(w, h):
bmi = float(w) / float(h)**2
return bmi
cal_BMI(70,1.7)
cal_BMI(h=1.73, w=70)
#BMI=w/h**2

def cal_BMI( w=70, h=1.73):
"""
w輸入kg
h輸入公尺
"""
bmi = float(w) / float(h)**2
return bmi
cal_BMI()
def add(a , b):
sum = a + b
return sum
add(2,555)
def repaly_word(b):
print(b)
print("我想你")
repaly_word("真的嗎")
repaly_word("a")
def 加法(a,b):
result = a + b
return result
加法(9,9)

12.第三個動手做:打造訂餐系統

當程式以函數包起來後,使用者只要呼叫函數,輸入對應的引數,即可得到結果,不需要在意裡面的細節囉

def 訂餐(13號餐,數量):
if13號餐 == 1:
price = 數量*60
elif13號餐 == 2:
price = 數量*70
elif13號餐 == 3:
price = 數量*80
else:
print("請選擇1至3號餐,輸入1個數字即可,謝謝")
return f"您選的是{13號餐}號餐, 數量是{數量}個,金額是{price}元"
訂餐(2,3)
訂餐(2,9)

13.用來個翻譯吧

來體驗怎麼使用外部模組

13-2.Python google翻譯

  1. google搜尋python google 翻譯
  2. 看文章程式碼
  3. 回頭找模組的官方文件(或github的說明文件),拓展想要的應用
!pip install googletrans==3.1.0a0
from googletrans import Translator

translator = Translator()

translator.translate('今晚我要來點真主單的紅茶拿鐵加珍珠', dest='en').text
print('English:', translator.translate('水之呼吸', dest='en').text)
print('Japanese:', translator.translate('水之呼吸', dest='ja').text)
print('Korean:', translator.translate('水之呼吸', dest='ko').text)

13-2. 翻譯轉語音

  1. google搜尋python google 文字轉語音
  2. 看文章程式碼
  3. 回頭找模組的官方文件(或github的說明文件),拓展想要的應用
!pip install gtts
from gtts import gTTS
import os

mytext = 'Convert this Text to Speech in Python'

language = 'en'
mygTTS = gTTS(text=mytext, lang=language, slow=False)
mygTTS.save("output.mp3")

# Play the converted file
os.system("start output.mp3")

13-3.把翻譯+語音串起來

!pip install googletrans==3.1.0a0
!pip install gtts
from googletrans import Translator
from gtts import gTTS
import os

def google_text_to_speak(text, to_speak_language='en'):
translator = Translator()
ttext = translator.translate(text, dest=to_speak_language).text
tts = gTTS(text= ttext, lang=to_speak_language)
tts.save(f'{text} {to_speak_language}.mp3')

if __name__ == "__main__":
google_text_to_speak("今晚打咚咚")
google_text_to_speak("本節目由五洲製藥贊助撥出",'ja')
google_text_to_speak("今晚打老虎")
google_text_to_speak("今晚打老虎",to_speak_language = 'ja')
import googletrans
print(googletrans.LANGCODES)

reference