Try   HackMD

111-07-16 Python入門實作班上課記錄

tags: python
# if 3 > 4:
#     print('3 > 4 = yes')
# else:
#     print('3 > 4 = no')

# if 6 > 5:
#     print('6 > 5 = yes')
# else:
#     print('6 > 5 = no')

# if 100 > 99:
#     print('100 > 99 = yes')
# else:
#     print('100 > 99 = no')

# 函式不會主動執行,必須透過呼叫的動作才會執行(def=define)
def compare(n1, n2):  # 定義函式,函式名稱compare,有兩個參數,n1和n2(也就是函式內的變數)
    if n1 > n2:
        print(n1, '>', n2, ' = yes')
    else:
        print(n1, '>', n2, ' = no')

compare(8, 9)  # 函式呼叫
compare(88, 66)
compare(188, 66)
compare(288, 266)
compare(88, 666)
compare(8, 466)

print('---------------- 分隔線 -------------------')
def swap(n1, n2):
    print(n2, n1)

swap(3, 4)
print('---------------- 分隔線 -------------------')
def showMe():
    print('I\'m Aaron')

showMe()

def show3num(n1, n2, n3):
    print(n1, n2, n3)

show3num(1, 2, 3)
print('---------------- 分隔線 -------------------')

def plus(n1, n2, n3):
    print('總合為:', n1 + n2 + n3)

    return 10 # 將結果往外傳給呼叫方

plus(4, 5, 6)
plus(40, 50, 60)
print('---------------- 分隔線 -------------------')

# 將兩組各三個數字,做完加總後再相乘
a = plus(1, 2, 3)
b = plus(4, 5, 6)
c = plus(14, 25, 36)
print(a * b * c)

print('---------------- 分隔線 -------------------')

def swapV2(n1, n2):
    return n2, n1

n1 = 1
n2 = 2
n1, n2 = swapV2(n1 ,n2)
print(n1, n2)

print('---------------- 分隔線 -------------------')
# 兩個數字比大小,印出比較大的那個
def max(n1, n2):
    return n1 if n1 > n2 else n2

print(max(7, 100))
print(max(70, 10))

abc = max
print(abc(99, 88))

def plus(n1, n2):
    return n1 + n2

def mux(n1, n2):
    return n1 * n2

def div(n1, n2):
    return n1 / n2

def min(n1, n2):
    return n1 - n2

def party(n1, n2, n3):
    return n1(n2, n3)

print(party(plus, 2, 3))
print(party(mux, 2, 3))
print(party(div, 2, 3))
print(party(min, 2, 3))

print('---------------- 分隔線 -------------------')

# def plus(n1, n2):
#     return n1 + n2

plusV2 = lambda n1, n2: n1 + n2
print(plusV2(7, 9))
    
print('---------------- 分隔線 -------------------')

hello = lambda n1: (2 if n1 %2 == 0 else 3) ** 2
print(hello(9999999))

a1 = 3

def test():
    a1 = 5
    print(a1)

test()
print(a1)

print('---------------- 分隔線 -------------------')

def test(n1):
    if n1 % 2 == 0:
        return
    print('hello')    
    return  # 函式結束並回傳1
    return 2
    return 3

print(test(1))

# 函式裡面只要有出現yield關鍵字,那該函式只會回傳generator(產生器)物件
def testV2():
    yield 1
    yield 2
    yield 3

g = testV2() # 回傳generator物件

next(g)
next(g)
next(g)
# next(g) # 這裡會產生StopIteration例外,程式會中斷執行

for n in g:
    print(n)

def myRange(n1, n2):
    while n1 < n2:
        yield n1
        n1 += 1

for i in myRange(1, 10):
    print(i)

print('---------------- 分隔線 -------------------')
# 階乘
# 3的階乘=1 x 2 x 3= 6
# 4的階乘=24

def factorial(n1):
    result = 1 # 區域變數
    for i in range(1, n1 + 1): # i= 1, 2, 3, 4.....etc
        result = result * i

    return result

a = int(input('請輸入一個數字:'))
result = factorial(a) # result為全域變數

print(a, '的階乘為', result)

print('---------------- 分隔線 -------------------')

a123 = 3 # 

def t():
    a123 = 5
    print(a123) 

t()
print(a123)

print('---------------- 分隔線 -------------------')


a = [10, 3, 60, 7, 8]
a.sort(reverse=True)
print(a)



中場練習

  1. Python有哪些群集資料型態?
    ​​​List, Set, Dict, Tuple
    
  2. lambda
    ​​​建立邏輯單純的匿名函式
    
  3. 定義函式的關鍵字是什麼?
    ​​​def
    
  4. range(3, 5)可以得到哪些數字?
    ​​​3, 4
    
  5. 哪個函式可以用來接收使用者的鍵盤輸入?
    ​​​input()
    
  6. 如何寫出一個無窮迴圈?
    ​​​while True:
    ​​​   pass
    
  7. len()函式的功用為何?
    ​​​計算群集資料的元素數量
    
  8. [1, 2, 3, 4, 5]如何透過索引切片取得[5, 4, 3, 2, 1]
    ​​​[::-1]
    
  9. pass關鍵字的功用是什麼?
    ​​​該語法對程式執行結果沒有影響,其作用是讓目前暫未開發的Python程式碼保持結構的完整,以免無法執行
    

Python類別與物件

class Car:
    def run(self):
        print('I\' running')

myCar = Car() # 建立物件

myCar.color = 'red'  # 建立物件變數(屬性)

print(myCar.color)

myCar.run()  # 呼叫物件方法


class Car:
    def __init__(self): # 建構式,建立物件時會自動被呼叫
        print('hello')

    def __str__(self):
        return 'I\'m car.'

    def run(self):
        print('I\' running')

myCar = Car() # 建立物件
myCar.color = 'red'  # 建立物件變數(屬性)
print(myCar.color)
myCar.run()  # 呼叫物件方法

print(str(myCar))

實務練習

透過政府的OpenData取得快篩剩餘量

下載網址:https://data.gov.tw/dataset/152408

import csv

with open('Fstdata.csv', encoding="utf8") as csvfile:
    rows = csv.reader(csvfile) # 解析csv檔案內容

    for row in rows:
        print(row[1], '剩餘量:',row[7])

猜數字遊戲

猜0~9之間的四個數字,如果當中有一個數字一樣,位置也一樣,得到1A,如果數字一樣,但位置不一樣,得到1B,直到4A完成遊戲,並記錄總共猜了幾次才完成。

import random elem = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] random.shuffle(elem) answer = ''.join(elem[0:4]) print('answer=', answer) count = 0 # 紀錄次數 while True: user = input('請輸入四個數字:') count += 1 # 檢查數字是否有重複:利用set元素不重複的特性,把四個數字拆開放到set後,如果長度為4,則表示沒有出現重複的數字 if len(set(user)) != 4: print('數字不可重複') continue # 回到迴圈開頭重新輸入 if user == answer: print('猜對了, 總共猜了', count, '次') break else: howManyA = 0 howManyB = 0 if answer[0] == user[0]: howManyA += 1 if answer[1] == user[1]: howManyA += 1 if answer[2] == user[2]: howManyA += 1 if answer[3] == user[3]: howManyA += 1 if user[0] in answer and answer[0] != user[0]: howManyB += 1 if user[1] in answer and answer[1] != user[1]: howManyB += 1 if user[2] in answer and answer[2] != user[2]: howManyB += 1 if user[3] in answer and answer[3] != user[3]: howManyB += 1 print(str(howManyA) + 'A' + str(howManyB) + 'B')