Basic Python

python version

>python --version
Python 3.6.0 :: Anaconda 4.3.1 (64-bit)

>python
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("This line will be printed.")

python กับการย่อหน้าที่ถูกต้อง นั้นใช้ 4 space

x = 1
if x == 1:
    # indented four spaces
    print("x is 1.")

Variable และ Type

myint = 7
print(myint)

isinstance(myint,float)
isinstance(myint,int)


myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)

mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)


one = 1
two = 2
three = one + two
print(three)

hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)

Lists [ ]

คล้ายกับ array สามารถ เก็บตัวแปรชนิดใดก็ได้

mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

# prints out 1,2,3
for x in mylist:
    print(x)

Index ของ list

mylist = [1,2,3]
print(mylist[0])
print(mylist[1])
print(mylist[2])
print(mylist[3])

Basic Operator

number = 1 + 2 * 3 / 4.0
print(number)

remainder = 11 % 3
print(remainder)

squared = 7 ** 2
cubed = 2 ** 3

helloworld = "hello" + " " + "world"
print(helloworld)


even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers

print([1,2,3] * 3)

String Format

  • %s string
  • %d integer
  • %f float
  • %<number of digits>f
  • %x/%X integer ในรูปแบบฐาน 16 (Hex representation)
# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)

# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))


data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."

print(format_string % data)

Basic String Operation

สามารถประกาศ string ภายใน " " หรือ ' '

astring = "Hello world!"
astring2 = 'Hello world!'


print(astring.index("o"))
print(astring.count("l"))
print(astring[3:7])
print(astring[3:7:2])
print(astring[::-1])
print(astring.upper())
print(astring.lower())
afewwords = astring.split(" ")
print(afewwords)

Condition

x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

Boolean operators and/or

name = "John"
age = 23
if name == "John" and age == 23:
    print("Your name is John, and you are also 23 years old.")

if name == "John" or name == "Rick":
    print("Your name is either John or Rick.")

"IN" operator

name = "John"
if name in ["John", "Rick"]:
    print("Your name is either John or Rick.")

"IS" operator ==

x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False

"for" Loop

primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

# Prints out the numbers 0,1,2,3,4
for x in range(5):
    print(x)

# Prints out 3,4,5
for x in range(3, 6):
    print(x)

# Prints out 3,5,7
for x in range(3, 8, 2):
    print(x)

"while" Loop

# Prints out 0,1,2,3,4

count = 0
while count < 5:
    print(count)
    count += 1  # This is the same as count = count + 1

"Break" และ "continue" statement

  • break ใช้สำหรับ ออก for loop หรือ while loop เป็นการสิ้นสุดการทำงาน
  • continue ใช้ออกจาก current block ที่ทำงาน กลับไปยัง for / while
# Prints out 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)

"else"

elseจะทำงาน เมื่อ เงื่อนไขของ loop "for" หรือ "while" เป็นเท็จ

# Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))

# Prints out 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("this is not printed because for loop is terminated because of break but not due to fail in condition")

การสร้าง function

def my_function():
    print("Hello From My Function!")

my_function()


def sum_two_numbers(a, b):
    return a + b

sum_two_numbers(1,2)

class และ object

Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()
myobjectx.variable


myobjecty = MyClass()
myobjecty.variable = "yackity"

print(myobjectx.variable)
print(myobjecty.variable)

myobjectx.function()

Dictionary

ทำหน้าเก็บข้อมูลได้คล้ายกับ list แต่จะเก็บรูปแบบ key, value ไม่ใช้ index

phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)

phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}
print(phonebook)

del phonebook["John"]
print(phonebook)

การวนลูปอ่านค่าใน Dictionary

การวนแต่ละครังสามารถดึงค่าของ key,value มาพร้อมกัน

phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))

Module และ package

Modules ในภาษา python คือ file ที่มีนามสกุล .py ภายใน module จะเป็นการ implement function การเรียกใช้งาน จะใช้คำสั่ง import` เพื่อดึงมาใช้งาน

# import the library
import urllib

# use it
urllib.urlopen(...)

# ดูว่าใน modules มีฟังก์ชั่นอะไรบ้าง
dir(urllib)

#อ่าน help ของ function
help(urllib.urlopen)

Package เป็น directory ธรรมดา ที่ภายในมี file ที่มีชื่อว่า __init__.py และ modules ที่สร้างขั้น ทำหน้าเป็น namespace และใช้คำสั่ง import function เช่นเดียวกันแต่ต้องมีการระบุ namespace ด้วยชื่อของ package

import foo.bar

นอกจากการใช้ import สามารถใช้ from

from foo import bar

results matching ""

    No results matching ""