- python.org/doc/
- docs.python.org – The Python Tutorial
- w3schools.com – Python Tutorial
ดูพาทที่ติดตั้ง Python
>>> import os >>> import sys >>> os.path.dirname(sys.executable) 'C:\\Python39'
Package
list package
> python -m pip list
> conda list
อัพเดท pip (บน Windows ให้ Run as administrator)
> python -m pip install --upgrade pip
แต่ถ้าอัพเกรดแล้ว pip พัง แก้ไขโดย
py -m ensurepip --default-pip
Python script header
#!/usr/bin/python
Pythom main
if __name__ == '__main__':
Python Try Except
- How to print an exception in Python? – Stack Overflow
- Python Try Except (w3schools.com)
- python – How can I write a `try`/`except` block that catches all exceptions? – Stack Overflow
try:
print(x)
except Exception as ex:
print(ex)
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
การคำนวณ
Arithmetic Operators
15/2 # หารปกติ, = 7.5 # Division 15%2 # mod, = 1 # Modulus 15//2 # div, = 7 # Floor division 2**3 # ยกกำลัง, = 8 # Exponentiation
Bitwise Operators
7 & 5 = 5 # AND 7 | 5 = 7 # OR 7 ^ 5 = 2 # XOR ~5 = -6 # NOT 1 << 5 = 32 # shift to left by 5 bits 32 >> 5 = 1 # shift to right by 5 bits
คำสั่ง print()
>>> print('Hello\nworld!')
Hello
world!
>>> print(f'Hello\nworld!')
Hello
world!
>>> print(b'Hello\nworld!')
b'Hello\nworld!'
>>> print(b'Hello\nworld!'.decode())
Hello
world!
name = "Jack"
print("Hello, {}.".format(name))
# Hello, Jack.
name = "Jack"
name2= "Tip"
print("Hello, {x}, {y}".format(x=name, y=name2))
# Hello, Jack, Tip
Data Types
Dictionary
d = {'key1': 100, 'key2': 200}
# {'key1': 100, 'key2': 200}
d['key1']
# 100
d.keys()
# dict_keys(['key1', 'key2'])
d.items()
# dict_items([('key1', 100), ('key2', 200)])
Tuple ใช้เก็บข้อมูลที่ไม่ต้องการเปลี่ยนค่า
t = (1,2,3) # tuple เป็น immutable เปลี่ยนค่าไม่ได้ print(t[0]) # 1
Set – A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
s = {1,1,1,2,2,2,3,1,2,3}
print(s)
# {1, 2, 3}
li = [1,1,1,2,2,2,3,1,2,3]
print(li)
# [1, 1, 1, 2, 2, 2, 3, 1, 2, 3]
s = set(li)
print(s)
# {1, 2, 3}
If statements
- w3schools Python If … Else
a = 20
b = 20
if a > b:
print("a is greater than b")
elif a == b:
print("a and b are equal")
else:
print("b is greater than a")
Short Hand If
a = 4
b = 3
if a > b: print("a is greater than b")
a = 4
b = 3
print("A") if a > b else print("B")
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
For Loops
- w3schools – Python For Loops
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) # apple # banana # cherry
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
# apple
# banana
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
# apple
# cherry
for x in range(5): print(x) # 0 # 1 # 2 # 3 # 4
for x in range(2, 10, 3): print(x) # 2 # 5 # 8
for x in range(3):
print(x)
else:
print("Finally finished!")
# 0
# 1
# 2
# Finally finished!
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
# 0
# 1
# 2
for x in [0, 1, 2]: pass
x = [1,2,3,4]
y = []
for num in x:
y.append(num**2)
print(y)
# [1, 4, 9, 16]
x = [1,2,3,4] y = [num**2 for num in x] print(y) # [1, 4, 9, 16]
while Loop
- w3schools – Python While Loops
i = 1 while i < 5: print(i) i += 1 # 1 # 2 # 3 # 4
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
# 1
# 2
# 3
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
# 1
# 2
# 4
# 5
i = 1
while i < 5:
print(i)
i += 1
else:
print("i is no longer less than 5")
# 1
# 2
# 3
# 4
# i is no longer less than 5
Functions
- w3schools – Python Functions
def my_function():
print("Hello from a function")
my_function()
# Hello from a function
def my_function(fname):
print("Hello " + fname)
my_function("Foo")
my_function("Bar")
# Hello Foo
# Hello Bar
def my_function(fname="UNKNOWN"):
print("Hello " + fname)
my_function()
# Hello UNKNOWN
def my_function(fname="UNKNOWN"):
"""This is my Docstring."""
print("Hello " + fname)
def my_function(*kids):
print(type(kids))
for item in kids:
print(item)
my_function("Foo", "Bar")
# <class 'tuple'>
# Foo
# Bar
Lambda
- w3schools – Python Lambda
x = lambda a : a ** 2 y = x(5) print(y) # 25
x = lambda a, b : a * b y = x(5, 6) print(y) # 30
def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(5)) print(mytripler(5)) # 10 # 15
Map
li = [1,2,3,4,5]
def time_two(var):
return var*2
print(time_two(5))
print(time_two(li))
print(list(map(time_two, li)))
# 10
# [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
# [2, 4, 6, 8, 10]
li = [1,2,3,4,5] print(list(map(lambda var: var*2, li))) # [2, 4, 6, 8, 10]
Filter
li = [1,2,3,4,5]
def is_even(num):
return num%2 == 0
print(is_even(2))
print(is_even(3))
print(list(filter(is_even,seq)))
# True
# False
# [2, 4]
li = [1,2,3,4,5] print(list(filter(lambda num: num%2 == 0, seq))) # [2, 4]
Useful Method
- w3schools – Python String Methods
st = "I am Jack." print(st.lower()) print(st.upper()) print(st.capitalize()) print(st.split()) # i am jack. # I AM JACK. # I am jack. # ['I', 'am', 'Jack.']
time delay
import time time.sleep(2.5) # This delays for 2.5 seconds