Course Description
หลักการทำงานของโปรแกรมคอมพิวเตอร์ ตัวแปลภาษา หลักการเขียนโปรแกรม
ชนิดของข้อมูล นิพจน์และการดำเนินการ คำสั่งการกำหนดค่า การรับข้อมูลและการแสดงผล
การควบคุมโปรแกรม โปรแกรมย่อย แถวลำดับ แฟ้มข้อมูล ฝึกปฏิบัติ
Principles of computer programs; translator; principles of Programming;
data types and operations; assignment, input and display data statements;
programs control; subprograms; array; file; practice
Course Schedule
Week 1: 4, 7 July 2022
- Course Introduction
- Getting Started with Python
Download Python
Download PyCharm
- Hello World!
- Handouts:
- Exercises:
Week 2: 11, 14 July 2022
OFF for Graduation Ceremony
Week 3: Basic Programming Concepts
Week 5: 1,4 Aug
if else: คำสั่งเลือกเงื่อนไข
คำสั่ง if เป็นคำสั่งที่ใช้ควบคุมการทำงานของโปรแกรมที่เป็นพื้นฐาน
คำสั่ง if เพื่อสร้างเงื่อนไขให้โปรแกรมทำงานตามที่เราต้องการเมื่อเงื่อนไขนั้นตรงกับที่เรากำหนด
รูปแบบ
if expression:
# statements
รูปแบบของการใช้งานคำสั่ง if และ expression
เป็นเงื่อนไขที่สร้างจากตัวดำเนินการประเภทต่าง ๆ ที่เป็น Boolean expression โดยโปรแกรมจะทำงานในบล็อคคำสั่ง if ถ้าหากเงื่อนไขเป็นจริง (True) ไม่เช่นนั้นโปรแกรมจะข้ามการทำงานไป
ตัว
x = 5
if x == 10:
print('x equal to 10')
y = 6
if y != 6:
print('y not equal to 6')
else:
print('y equal to 6')
m = 4
if m % 2 == 0 and m > 0:
print('m is even and positive numbers')
if 3 > 10:
print('This block isn\'t executed')
if..elif..else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
แบบฝึกปฏิบัติ
Week 7 (15, 18 Aug) Loop
For Loop
คำสั่ง for loop เป็นคำสั่งวนซ้ำที่ใช้ควบคุมการทำงานซ้ำๆ ในจำนวนรอบที่แน่นอน
Syntax
for i in sequence:
loop body
โดย i คือชื่อตัวแปรที่แสดงผลค่าต่อไปใน Sequence
ตัวอย่าง
for i in range(10):
print(i)
--- Output ---
0
1
2
3
4
5
6
7
8
9
ตัวอย่าง 1
for x in "banana":
print(x)
ผลลัพธ์ 1

ตัวอย่าง 2
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
ผลลัพธ์ 2

ตัวอย่าง
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
--- Output ---
???
# loop through string
site = 'marcuscode'
for n in site:
print(n)
# loop through list
names = ['Mateo', 'John', 'Eric', 'Mark', 'Robert']
for n in names:
print(n)
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
for n in numbers:
print(n)
--- Output ---
???
The While Loop
Syntax
while expression:
statement(s)
ตัวอย่าง 1
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello People")
ตัวอย่าง 2
i = 1
while i < 6:
print(i)
i += 1
ตัวอย่าง 3
# checks if list still
# contains any element
a = [1, 2, 3, 4]
while a:
print(a.pop())
ตัวอย่าง 4
# Prints all letters except 'e' and 's'
i = 0
a = 'geeksforgeeks'
while i < len(a):
if a[i] == 'e' or a[i] == 's':
i += 1
continue
print('Current Letter :', a[i])
i += 1
ตัวอย่าง 5
# break the loop as soon it sees 'e'
# or 's'
i = 0
a = 'geeksforgeeks'
while i < len(a):
if a[i] == 'e' or a[i] == 's':
i += 1
break
print('Current Letter :', a[i])
i += 1
ตัวอย่าง 6
a = int(input('Enter a number (-1 to quit): '))
while a != -1:
a = int(input('Enter a number (-1 to quit): '))
STRING
Strings in python are surrounded by either single quotation marks, or double quotation marks.
a = "Hello"
print(a)
Multiline Strings
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Strings are Arrays
a = "Hello, World!"
print(a[1])
String Length
a = "Hello, World!"
print(len(a))
Check String
txt = "The best things in life are free!"
print("free" in txt)
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
txt = "The best things in life are free!"
print("expensive" not in txt)
Slicing Strings
b = "Hello, World!"
print(b[2:5])
Slice From the Start
b = "Hello, World!"
print(b[:5])
Slice To the End
b = "Hello, World!"
print(b[2:])
Upper Case
a = "Hello, World!"
print(a.upper())
Lower Case
a = "Hello, World!"
print(a.lower())
Remove Whitespace
a = " Hello, World! "
print(a.strip()) # returns "Hello, World
Replace String
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Examples
Output 1
Hello
Hello
Hello
Hello, welcome to
the world of Python
Output 2
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am

Output 3
# Python String Operations
str1 = 'Hello'
str2 ='World!'
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
# Iterating through a string
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Output
3 letters found
List
List เป็นโครงสร้างข้อมูลแบบหนึ่งในภาษา Python
List นั้นเป็นตัวแปรประเภทหนึ่ง การใช้งานของมันจะเหมือนกับอาเรย์ในภาษาอื่น ๆ
การประกาศตัวแปร List
โดยกำหนดให้ค่า List อยู่ในเครื่องหมาย [ ] และมี , คั่นระหว่างค่า (items) แต่ละค่า
ตัวอย่าง
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
ตัวอย่างที่ 1: การเข้าถึงและแสดงค่าใน Lists
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
ผลลัพธ์ (Output)
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
การแก้ไขค่าใน List
ตัวอย่าง
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Output
Value available at index 2 :
1997
New value available at index 2 :
2001
Remove List Items
Remove()
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
pop()
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
del
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Output
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
clear()
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Add List Items
append()
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
insert()
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
extend()
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Loop Lists
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
List Comprehension
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Sort Lists
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
sort(reverse = True)
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
Function: โปรแกรมย่อย
การสร้าง Function
กำหนด def ตามตัวชื่อฟังก์ชัน เช่น
def my_function():
def คือ การกำหนดฟังก์ชัน
my_function() คือ ชื่อฟังก์ชัน (สามารถตั้งชื่อใด ๆ ให้สอดคล้องกับวัตถุประสงค์ของฟังก์ชันนั้น ๆ)
ตัวอย่าง
def my_function():
print("Hello from a function")
จากตัวอย่างข้างต้น เป็นการประกาศฟังก์ชันที่ชื่อว่า my_function() ที่ให้แสดงผล
Hello from a function
การเรียกใช้ฟังก์ชัน
def my_function():
print("Hello from a function")
//การเรียกใช้
my_function()
Arguments
คือการส่งค่าผ่านฟังก์ชัน เช่น
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
การกำหนด Arguments มากกว่า 1 ตัว
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary Arguments, *args
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Passing a List as an Argument
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits
Return Values
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9)
File I/O
ทำไมต้องไฟล์
เนื่องจากการจัดการข้อมูลถือความเป็นความจำเป็นพื้นฐานของการทำงานด้านการคอมพิวเตอร์ ไม่ว่าจะนำไปใช้ด้านจัดเก็บข้อมูล ประมวลผลข้อมูลมาก ๆ รวมทั้งการแก้ปัญหาด้วย Machine Learning ล้วนจำเป็นต้องเข้าใจการทำงานของ File พื้นฐาน
การเปิดไฟล์ด้วย open() function
การเปิดไฟล์ในรูปแบบต่าง ๆ
- ‘r’ : This mode indicate that file will be open for reading only
- ‘w’ : This mode indicate that file will be open for writing only. If file containing containing that name does not exists, it will create a new one
- ‘a’ : This mode indicate that the output of that program will be append to the previous output of that file
- ‘r+’ : This mode indicate that file will be open for both reading and writing
Let’s start
สร้างไฟล์ทดสอบ
ตั้งชื่อไฟล์ demofile.txt เพิ่มข้อความดังนี้
Love
Have
Happy
Joy
//Format
file = open(filename, mode)
//ตัวอย่าง
file = open("demofile.txt","r")
ตัวอย่างการใช้งาน read mode
# a file named "demofile", will be opened with the reading mode.
file = open('demofile.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
ตัวอย่างการใช้งาน write mode
# Python code to create a file
file = open('demofile.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
ตัวอย่างการใช้งาน append mode
# Python code to illustrate append() mode
file = open('demofile.txt', 'a')
file.write("This will add this line")
file.close()