พื้นฐาน Python 3
ตัวแปรและชนิดข้อมูล
ตัวแปรใช้สำหรับเก็บข้อมูล โดย Python ไม่ต้องประกาศชนิดข้อมูลล่วงหน้า
variables.py
1x = 10
2name = "Python"
3pi = 3.14
4is_active = Trueชนิดข้อมูลพื้นฐาน (Data Types)
conditionals.py
1# int : จำนวนเต็ม
2x = 10
3y = -5
4
5# float : จำนวนทศนิยม
6pi = 3.14
7
8# str : ข้อความ
9name = "Hello"
10
11# bool : ค่าจริง/เท็จ
12is_active = True
13is_done = False
14
15# list : รายการข้อมูล
16numbers = [1, 2, 3]
17
18# tuple : รายการแบบแก้ไขไม่ได้
19coordinates = (1, 2, 3)
20
21# dict : ข้อมูลแบบ key-value
22data = {"a": 1}การแสดงผลข้อมูล (print)
loops.py
1print("Hello World")
2print("ค่า x =", x)การรับค่าจากผู้ใช้ (input)
functions.py
1name = input("กรุณาใส่ชื่อ: ")
2print("สวัสดี", name)หมายเหตุ: ค่าที่รับจาก input() จะเป็นชนิด str เสมอ
การแปลงชนิดข้อมูล
files.py
1age = int(input("อายุ: "))
2height = float(input("ส่วนสูง: "))ตัวดำเนินการ (Operators)
ตัวดำเนินการทางคณิตศาสตร์
arithmetic.py
1a = 10 + 5 # บวก
2b = 10 - 5 # ลบ
3c = 10 * 5 # คูณ
4d = 10 / 5 #หาร
5e = 10 % 3 # หารเอาเศษตัวดำเนินการเปรียบเทียบ
comparison.py
1x = 10
2y = 5
3
4print(x == y) # เท่ากับ
5print(x != y) # ไม่เท่ากับ
6print(x > y) # มากกว่า
7print(x < y) # น้อยกว่า
8print(x >= y) # มากกว่าหรือเท่ากับ
9print(x <= y) # น้อยกว่าหรือเท่ากับเงื่อนไข if / elif / else
conditions.py
1score = 75
2
3if score >= 80:
4 print("เกรด A")
5elif score >= 70:
6 print("เกรด B")
7else:
8 print("ไม่ผ่าน")วนลูป (Loops)
for loop
for_loop.py
1# for loop
2for i in range(5):
3 print(i)while loop
while_loop.py
1i = 0
2while i < 5:
3 print(i)
4 i += 1โครงสร้างข้อมูล list
list.py
1numbers = [10, 20, 30]
2print(numbers[0])
3
4numbers.append(40)วนลูปผ่าน list
list_loop.py
1for n in numbers:
2 print(n)ฟังก์ชัน (Functions)
functions.py
1def add(a, b):
2 return a + b
3
4result = add(3, 5)
5print(result)การใช้โมดูล (Modules)
modules.py
1import math
2print(math.sqrt(16))
3
4# หรือ
5
6from math import sqrt
7print(sqrt(16))การจัดการข้อผิดพลาด (try / except)
error_handling.py
1try:
2 x = int("abc")
3except:
4 print("เกิดข้อผิดพลาด")ตัวอย่างโปรแกรมสรุป
summary.py
1def check_age(age):
2 if age >= 18:
3 return "ผู้ใหญ่"
4 else:
5 return "เด็ก"
6
7age = int(input("อายุ: "))
8print(check_age(age))