講者:黃丰嘉
Python 是一通用、直譯、物件導向的高階程式語言。
https://kknews.cc/news/nkkr3j3.html
腳本語言
直譯
vs.
編譯
# 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 將於 2020年停止維護
兩者互不相容
Python 3.x --- Cleaner and faster!
縮排!縮排!縮排!
單行註解
#This is a comment.
多行註解
"""This is a
multiline docstring."""
'''This is a
multiline docstring.'''
this_is_a_number = 1
ThisIsANumber = 1
請不要使用以下保留字命名!
>>> 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
x = 1 # int
y = 2.8 # float
z = 3+5j # complex
>>> x=1.23
>>> type(x)
<class 'float'>
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
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!" 去掉前後的空白
加 + 減 - 乘 *
除法
/ (浮點數除法)
4/2 輸出結果為 2.0
// (整數除法)
9//5 輸出結果為 1
次方 **
2**3 輸出結果為 8
取餘數 %
7%5 輸出結果為 2
賦值運算子 | 名稱 | 範例 | 相當於 |
---|---|---|---|
+= | 加法指定 | i+=8 | i=i+8 |
等於 ==
不等於 !=
大於 >
小於 <
大於等於 >=
小於等於 <=
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))
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 -> 參考到同一個櫃子
== -> 內容相同
in
not in
x = ["apple", "banana"]
print("banana" in x)
# returns True
because a sequence with the value "banana" is in the list
賦值運算子 | 名稱 | 範例 | 相當於 |
---|---|---|---|
&= | 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
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)
thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"
print(thistuple)
# the value is still the same.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
# add one item
thisset.update(["orange", "mango", "grapes"])
# add more than one item
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
安裝 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)
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秒
radius = eval(input("Enter a value for radius: "))
area = radius**2 * 3.14
print(area)
試著寫出 input 半徑 output 圓面積
圓周率: 3.14
radius = eval(input("Enter a value for radius: "))
area = radius**2 * 3.14
print(area)
試著寫出 input 半徑 output 圓面積
圓周率: 3.14
兩者皆能將字串轉換為整數
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
from math import pi
radius = eval(input("Enter a value for radius: "))
area = radius**2 * pi
print(area)
試著 把
圓周率 = 3.14用 python的函示庫取代
from math import pi
radius = eval(input("Enter a value for radius: "))
area = radius**2 * pi
print(area)
試著 把
圓周率 = 3.14用 python的函示庫取代
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) + "%")
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) + "%")
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.")
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
謝謝大家