Variables & Types
Variables & Types
Section titled “Variables & Types”ตัวแปร (variable) คือ “กล่องเก็บข้อมูล” ที่เราตั้งชื่อเพื่อเรียกใช้ซ้ำได้ Python มีชนิดข้อมูลพื้นฐาน 4 แบบที่ต้องรู้
ชนิดข้อมูลพื้นฐาน
Section titled “ชนิดข้อมูลพื้นฐาน”# str — ข้อความname = "สมชาย"product_code = "SKU-001"
# int — จำนวนเต็มquantity = 42year = 2024
# float — ทศนิยมprice = 199.50tax_rate = 0.07
# bool — True / Falseis_active = Truehas_discount = Falseตรวจสอบชนิดด้วย type()
Section titled “ตรวจสอบชนิดด้วย type()”print(type(name)) # <class 'str'>print(type(quantity)) # <class 'int'>print(type(price)) # <class 'float'>print(type(is_active)) # <class 'bool'>f-strings — จัดรูปแบบข้อความ
Section titled “f-strings — จัดรูปแบบข้อความ”# f-string ใช้ f"..." แล้วใส่ตัวแปรใน {}message = f"สินค้า {product_code} ราคา {price:.2f} บาท"print(message)# สินค้า SKU-001 ราคา 199.50 บาท
# จัดรูปแบบตัวเลขbig_number = 1234567print(f"{big_number:,}") # 1,234,567
# ใส่ expression ได้เลยtotal = quantity * priceprint(f"รวม {total:,.2f} บาท") # รวม 8,379.00 บาทNaming Convention
Section titled “Naming Convention”# ใช้ snake_case สำหรับตัวแปรและฟังก์ชันuser_name = "test" # ดีuserName = "test" # ไม่แนะนำ (camelCase)
# ค่าคงที่ใช้ UPPER_CASEMAX_RETRIES = 3API_BASE_URL = "https://api.example.com"ใน Google Sheets ไม่มี “ตัวแปร” แต่ใช้ cell reference แทน:
- ข้อความ: พิมพ์ตรงๆ ใน cell
- ตัวเลข: พิมพ์ตัวเลขใน cell
- Boolean:
TRUE/FALSE - ตรวจสอบชนิด: ใช้
=TYPE(A1)(1=number, 2=text)
SQL ใช้ data types ตอนสร้างตาราง:
CREATE TABLE products ( name VARCHAR(100), -- str quantity INT, -- int price DECIMAL(10,2), -- float is_active BOOLEAN -- bool);C ต้องประกาศชนิดข้อมูลก่อนใช้งาน:
char name[] = "Product";int quantity = 42;float price = 199.50f;// C ไม่มี bool ดั้งเดิม ใช้ stdbool.h#include <stdbool.h>bool is_active = true;