Python Advance

講者:黃丰嘉

What is Python ?

Python 是一通用、直譯、物件導向的高階程式語言。

https://kknews.cc/news/nkkr3j3.html

腳本語言

直譯

vs.

編譯

1. 通用:撰寫任何工作的程式碼

2. 直譯:直譯器轉譯與執行(一次一行)

3. 物件導向:有利於開發可重複的軟體

# trips/models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True)
    photo = models.URLField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

Python 2.7 v/s 3.7

  • Python 2.7 將於 2020年停止維護

  • 兩者互不相容

  • Python 3.x    --- Cleaner and faster!

撰寫Python

一定要注意的事!

  • Indentation aware

縮排!縮排!縮排!

Comments 註解

單行註解
#This is a comment.    

多行註解
"""This is a
multiline docstring."""    

'''This is a
multiline docstring.'''

Variables Names

變數命名

  • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
  • Rules for Python variables:
    • 開頭:不能為數字
    • 使用 A-z, 0-9, and _ 命名 (底線 underscore)
    • 駝峰式大小寫 Case-sensitive
    • Python 會辨別大小寫
this_is_a_number = 1

ThisIsANumber = 1

保留字 (Reserved Word)

請不要使用以下保留字命名!

>>> import keyword

>>> keyword.kwlist

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

 exit() 離開 python 回到 cmd

Numbers 數字

  • Three numeric types in Python:
    • int
    • float
    • complex
x = 1        # int
y = 2.8      # float
z = 3+5j     # complex

>>> x=1.23
>>> type(x)
<class 'float'>

Specify a Variable Type

強制轉換型別

  • int()
  • float()
  • str()
a = int(2.8)     # a will be 2
x = float(1)         # x will be 1.0
z = float("3")       # z will be 3.0
w = float("4.2")     # w will be 4.2
y = str(2)        # y will be '2'
z = str(3.0)      # z will be '3.0' 


>>> print('哈囉'+123)

>>> print('哈囉')
哈囉

>>> print('哈囉'+str(123))
哈囉123

Strings 字串

a = "Hello, World!"
print(a[1])              #e
print(a[2:5])            #llo
print(len(a))            #13
print(a.lower())             #hello, world!
print(a.upper())             #HELLO, WORLD!
print(a.replace("H", "J"))        #Jello, World!

>>> a = "Hello, World!"
>>> print(a.split(","))        #['Hello', ' World!']
>>> b = a.split(",")
>>> type(b)                    #<class 'list'>

a = " Hello, World! "
print(a.strip())     #"Hello, World!" 去掉前後的空白

Operators

運算子

Arithmetic operators

算術運算子

  • 加 +       減 -       乘 *

  • 除法

    • /  (浮點數除法)

      • 4/2 輸出結果為 2.0

    • // (整數除法)

      • 9//5 輸出結果為 1

  • 次方 **

    • 2**3 輸出結果為 8

  • 取餘數 %

    • 7%5 輸出結果為 2

賦值運算子 名稱 範例 相當於
+= 加法指定 i+=8 i=i+8

Comparison Operators

比較運算子

  • 等於 ==

  • 不等於 !=

  • 大於 >

  • 小於 <

  • 大於等於 >=

  • 小於等於 <=

Logical Operators

邏輯運算子

  • and

  • or

  • not

>>> x = 5

>>> print(x > 3 and x < 10)

>>> print((x > 10) or (x % 2 == 0))

>>> print(not(x > 3 and x < 10))

#補充:Identity Operators

  • is

  • is not

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)    # True because z is the same object as x

print(x is y)    # False because x is not the same object as y, 
                    even if they have thew same content

print(x == y)    # True because x is equal to y

# the difference betweeen "is" and "==": 
    is -> 參考到同一個櫃子
    == -> 內容相同

#補充:Membership Operators

  • in

  • not in

x = ["apple", "banana"]

print("banana" in x)

# returns True 
because a sequence with the value "banana" is in the list

#先不管

Bitwise Operators

賦值運算子 名稱 範例 相當於
&= AND x &= 3 x = x & 3
|= OR x |= 3 x = x | 3
^= XOR x ^= 3 x = x ^ 3
>>= Signed right shift x >>= 3 x = x >> 3
<<= Zero fill left shift x <<= 3 x = x << 3
~ NOT

https://www.w3schools.com/python/python_operators.asp

資料結構

資料結構

  • List is a collection which is ordered and changeable.
    • Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable.
    • Allows duplicate members.
  • Set is a collection which is unordered and unindexed.
    • No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed.
    • No duplicate members.

List

  • List is a collection which is ordered and changeable.
    • Allows duplicate members.
    • method: append(), insert(),remove(), reverse(), sort(), pop()...
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Tuple

  • Tuple is a collection which is ordered and unchangeable.
    • Allows duplicate members.
thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"

print(thistuple)        
# the value is still the same.

Set

  • Set is a collection which is unordered and unindexed.
    • No duplicate members.
    • method: add(), update(), len(), discard(), pop()...
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")    
# add one item

thisset.update(["orange", "mango", "grapes"])    
# add more than one item

Dictionary

  • Dictionary is a collection which is unordered, changeable and indexed.
    • No duplicate members.
    • method: get(), items(), pop()...
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }

x = thisdict["model"]
y = thisdict.get("model")
print(x,y)                # Mustang Mustang

thisdict["year"] = 2018
print(thisdict)

for x, y in thisdict.items():
  print(x, y)

純量

  • 補充

>>> x = 12.63718

>>> int(x)
12

>>> round(x,2)
12.64

>>> round(x,3)
12.637


sum = 1 + 2 + 3 + 4 + \
      5 + 6

sum = 1 + 2 + 3 + 4 + 5 + 6
將 x=1 , y=2 內的值對調

x = 1
y = 2
temp = x
x = y
y = temp

vs.

x, y = y, x

打開 Linux Command Line

安裝 python

~$ sudo apt-get update
~$ sudo apt-get install python3.6


~$ python -V    查看 python 版本    (大寫V)
~$ python --version
~$ python3

>>> print("Hello world")

>>> print(input("enter your name: "))

>>> exit()

Simple input and output

[ 方法一 ]   直接執行  (Python shell)

~$ vim test.py


name = input("Please enter your name: ")
print("hello, " + name)


i            進入修改模式
Esc + :wq    儲存後並關閉


~$ python3 test.py    執行

~$ vim test.py    再次修改

[ 方法二 ]   寫成腳本再執行 (Python script)

Lab 0 輸出

this_a_string = " SIRLA "
print(this_a_string + " Enlightened ")
print(this_a_string * 3)

請試寫出把輸入的數字乘以2並輸出

print(int(input()) * 2)

或

val = int(input("Please enter a number: "))
print(val * 2)

或

val = input("Please enter a number: ")
print(int(val) * 2)

請試寫出把輸入的數字乘以2並輸出

seconds = int(input("輸入秒數: "))
minutes = seconds // 60
remainingSec = seconds % 60

print(seconds,"秒為",minutes,"分鐘又",remainingSec,"秒")
或
print(str(seconds)+"秒為"+str(minutes)+"分鐘又"+ \
 str(remainingSec)+"秒")

試著寫出 以秒表示總時間長,取得分鐘數及剩餘的秒數。如:500秒為8分鐘又20秒

seconds = int(input("輸入秒數: "))
minutes = seconds // 60
remainingSec = seconds % 60

print(seconds,"秒為",minutes,"分鐘又",remainingSec,"秒")
或
print(str(seconds)+"秒為"+str(minutes)+"分鐘又"+ \
 str(remainingSec)+"秒")

試著寫出 以秒表示總時間長,取得分鐘數及剩餘的秒數。如:500秒為8分鐘又20秒

Lab 1 計算圓面積

radius = eval(input("Enter a value for radius: "))
area = radius**2 * 3.14

print(area)

試著寫出       input 半徑    output 圓面積

圓周率: 3.14

Lab 1 計算圓面積

radius = eval(input("Enter a value for radius: "))
area = radius**2 * 3.14

print(area)

試著寫出       input 半徑    output 圓面積

圓周率: 3.14

eval   V/S   int

兩者皆能將字串轉換為整數

  • int : 無法運作於非整數的字串
    • int("3.4") 產生錯誤
    • int("003") 將會回傳 3
  • eval : 可處理較複雜的轉換
    • eval("3+4") 將會回傳 7
    • eval("003") 產生錯誤

懂得用模組,人生就是彩色的..

sudo apt-get install python-pip

import [module_name] as [Custom_name]

import math
print(math.pi)

import math as m     # 為 math 模組取別名為 m
print(m.pi)


from [module_name] import [name1, name2, ... nameN]

from math import pi
print(pi)

http://dokelung-blog.logdown.com/posts/243281-notes-django-python-modules-and-kits

https://docs.python.org/3/library/math.html

Lab 2 計算圓面積

from math import pi

radius = eval(input("Enter a value for radius: "))
area = radius**2 * pi

print(area)

試著 把

圓周率 = 3.14用 python的函示庫取代

Lab 2 計算圓面積

from math import pi

radius = eval(input("Enter a value for radius: "))
area = radius**2 * pi

print(area)

試著 把

圓周率 = 3.14用 python的函示庫取代

Lab1  打怪

  • input 怪物閃避值
  • output 命中率
  • 初始命中值 = 800
  • 命中率 = (角色命中值 - 怪物閃避值)/1000 * 100%
hit_value = 800
dodge_value = int(input("Input monster's dodging value: "))

# Input your code here
hit_rate = (hit_value - dodge_value) / 1000 * 100
print("Your hit rate is: " + str(hit_rate) + "%")

Lab 1 打怪

  • input 怪物閃避值
  • output 命中率
  • 初始命中值 = 800
  • 命中率 = (角色命中值 - 怪物閃避值)/1000 * 100%
hit_value = 800
dodge_value = int(input("Input monster's dodging value: "))

# Input your code here
hit_rate = (hit_value - dodge_value) / 1000 * 100
print("Your hit rate is: " + str(hit_rate) + "%")

Lab 1+ 打怪前的預備動作

Tips: random + if / else

import random
random.randint(0, 2)    # 在 0, 1, 2 中取亂數

random.randint(1, 2)    # 在 1, 2 中取亂數
num = int(input("enter your number: "))

if num > 0:
    print("Positive")
elif num == 0:
    print("equal 0")
else: # num < 0
    print("Negative")

~ 思考一下 ~

import random

girlfriend_probability = random.randint(0, 100)

if girlfriend_probability == -1:
    print("You wil have a girlfriend soon.")
else:
    print("You're on your own.")
    

while  Loops    v.s.    for  Loops

  • while : 不知道要跑幾次
  • for : 知道要跑幾次
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1 

# 印出 1 2 3
i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

# 印出 1 2 4 5 6

break -> 程式中止,不跑了
continue -> 跳過該段程式,繼續下一個

生成一個有10隻怪物的關卡,每隻怪物都有自己的閃避值
input: 每隻怪物閃避值
output: 印出10隻怪物的閃避值

dodge_list = []
for i in range(10):
    dodge_value = int(input("請輸入怪物的閃避值: "))
    dodge_list.append(dodge_value)

for dodge_value in dodge_list:
    print(dodge_value)

或


dodge_list = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]

for i in range(10):
    print(dodge_list[i])
#list:  append()、remove()、pop()

生成一個有10隻怪物的關卡,每隻怪物都有自己的閃避值
input: 每隻怪物閃避值
output: 印出10隻怪物的閃避值

dodge_list = []
for i in range(10):
    dodge_value = int(input("請輸入怪物的閃避值: "))
    dodge_list.append(dodge_value)

for dodge_value in dodge_list:
    print(dodge_value)

或


dodge_list = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]

for i in range(10):
    print(dodge_list[i])
#list:  append()、remove()、pop()

ITSA 練習題

while True:
    x = str(input())
    x_reverse = x[::-1]
    if x_reverse == x:
        print("YES")
    else:
        print("NO")

Solution

while True:
    n = eval(input())
    pi_even = 0
    pi_odd = 0
    
    if n > 0:
        for k in range(3,2*n+1,4):
            pi_even = pi_even - (4/k)
            for p in range(5,2*n+1,4):
                pi_odd = pi_odd + (4/p)
        print(4 + pi_even + pi_odd)
    else:
        print("")

Solution

補充教材

  • Python 3.7.0 官方文件:https://docs.python.org/3/
  • w3schools 線上教學:https://www.w3schools.com/python/default.asp
  • 一小時Python入門:https://kopu.chat/2017/01/18/%e4%b8%80%e5%b0%8f%e6%99%82python%e5%85%a5%e9%96%80-part-1/

謝謝大家

Python for Beginner

By BessyHuang

Python for Beginner

  • 402