Hello World — โปรแกรม Python แรกของคุณ
โปรแกรมที่ง่ายที่สุด
หัวข้อที่มีชื่อว่า “โปรแกรมที่ง่ายที่สุด”ใน TypeScript คุณมักต้องเซ็ตโปรเจกต์ก่อนถึงจะเขียนโค้ดบรรทัดแรกได้ ส่วนใน Python จากศูนย์ถึงรันได้จริงใช้แค่ไฟล์เดียวกับคำสั่งเดียว
// hello.tsconst name: string = "TypeScript Developer";console.log(`Hello, ${name}!`);
// Run: npx ts-node hello.ts// Output: Hello, TypeScript Developer!# hello.pyname: str = "TypeScript Developer"print(f"Hello, {name}!")
# Run: python3 hello.py# Output: Hello, TypeScript Developer!ฟังก์ชัน print
หัวข้อที่มีชื่อว่า “ฟังก์ชัน print”console.log ของ TypeScript เทียบได้กับ print ของ Python ทั้งคู่รับหลาย argument เหมือนกัน แต่รายละเอียดต่างกันอยู่:
// TypeScript console.logconsole.log("a", "b", "c"); // a b c (space separated)console.log("count:", 42); // count: 42console.log(`sum = ${1 + 2}`); // sum = 3 (template literal)# Python printprint("a", "b", "c") # a b c (space separated)print("count:", 42) # count: 42print(f"sum = {1 + 2}") # sum = 3 (f-string)
# print has keyword args:print("a", "b", sep="-") # a-b (custom separator)print("loading", end="...") # loading... (no newline)F-strings — template literals ของ Python
หัวข้อที่มีชื่อว่า “F-strings — template literals ของ Python”f-string ของ Python (f"...") ทำหน้าที่เดียวกับ template literal ของ TypeScript (`...`) วิธีใช้คือเติม f ไว้หน้า string แล้ววาง expression ไว้ใน {}
// TypeScript template literalconst user = { name: "Alice", age: 30 };const msg = `${user.name} is ${user.age} years old`;console.log(msg); // Alice is 30 years old
// Format numberconst pi = 3.14159;console.log(`pi ≈ ${pi.toFixed(2)}`); // pi ≈ 3.14# Python f-stringuser = {"name": "Alice", "age": 30}msg = f"{user['name']} is {user['age']} years old"print(msg) # Alice is 30 years old
# Format specifier inside {}pi = 3.14159print(f"pi ≈ {pi:.2f}") # pi ≈ 3.14
# Any expression worksprint(f"2 + 2 = {2 + 2}") # 2 + 2 = 4การรัน script
หัวข้อที่มีชื่อว่า “การรัน script”# TypeScript# 1. Compile and runtsc hello.ts && node hello.js
# 2. Direct with ts-nodenpx ts-node hello.ts
# 3. Via npm script (package.json)npm start# Python# 1. Direct — no compilation steppython3 hello.py
# 2. Make the file executable (Unix)chmod +x hello.py # add #!/usr/bin/env python3 as line 1./hello.py
# 3. Run as a module (inside a package)python3 -m mypackage.helloEntry-point guard: if __name__ == "__main__":
หัวข้อที่มีชื่อว่า “Entry-point guard: if __name__ == "__main__":”นี่คือ pattern ของ Python ที่ไม่มีตัวเทียบตรง ๆ ใน TypeScript จึงควรอธิบายให้ละเอียดสักหน่อย
เวลา Python รันไฟล์โดยตรงด้วย python3 hello.py interpreter จะตั้ง __name__ ของ module นั้นเป็น string "__main__" แต่ถ้าไฟล์อื่นเรียก import hello ค่า __name__ จะกลายเป็น "hello" ซึ่งก็คือชื่อ module แทน
ดังนั้น if __name__ == "__main__": จึงแปลว่า “รันโค้ดในนี้เฉพาะตอนไฟล์นี้เป็น entry point อย่าไปรันตอนโดน import”
// TypeScript: no direct equivalent// In Node, top-level code always runs when the file is imported// You work around this with explicit exports:
export function greet(name: string) { return `Hello, ${name}!`;}
// This runs unconditionally on import — often undesirable:// console.log(greet("world"));# Python: the entry-point guarddef greet(name: str) -> str: return f"Hello, {name}!"
if __name__ == "__main__": # This block ONLY runs when you do: python3 hello.py # It does NOT run when another file does: import hello print(greet("world"))Script แรกฉบับสมบูรณ์
หัวข้อที่มีชื่อว่า “Script แรกฉบับสมบูรณ์”# hello.py — a complete first Python script
def greet(name: str) -> str: """Return a personalised greeting.""" return f"Hello, {name}!"
def main() -> None: names = ["Alice", "Bob", "TypeScript Developer"] for name in names: message = greet(name) print(message)
# f-string formatting count = len(names) print(f"\nGreeted {count} people.")
if __name__ == "__main__": main()Loading Python runtime (first run only)…