ข้ามไปยังเนื้อหา

Hello World — โปรแกรม Python แรกของคุณ

ใน TypeScript คุณมักต้องเซ็ตโปรเจกต์ก่อนถึงจะเขียนโค้ดบรรทัดแรกได้ ส่วนใน Python จากศูนย์ถึงรันได้จริงใช้แค่ไฟล์เดียวกับคำสั่งเดียว

TypeScript
// hello.ts
const name: string = "TypeScript Developer";
console.log(`Hello, ${name}!`);
// Run: npx ts-node hello.ts
// Output: Hello, TypeScript Developer!
Python
# hello.py
name: str = "TypeScript Developer"
print(f"Hello, {name}!")
# Run: python3 hello.py
# Output: Hello, TypeScript Developer!

console.log ของ TypeScript เทียบได้กับ print ของ Python ทั้งคู่รับหลาย argument เหมือนกัน แต่รายละเอียดต่างกันอยู่:

TypeScript
// TypeScript console.log
console.log("a", "b", "c"); // a b c (space separated)
console.log("count:", 42); // count: 42
console.log(`sum = ${1 + 2}`); // sum = 3 (template literal)
Python
# Python print
print("a", "b", "c") # a b c (space separated)
print("count:", 42) # count: 42
print(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-string ของ Python (f"...") ทำหน้าที่เดียวกับ template literal ของ TypeScript (`...`) วิธีใช้คือเติม f ไว้หน้า string แล้ววาง expression ไว้ใน {}

TypeScript
// TypeScript template literal
const user = { name: "Alice", age: 30 };
const msg = `${user.name} is ${user.age} years old`;
console.log(msg); // Alice is 30 years old
// Format number
const pi = 3.14159;
console.log(`pi ≈ ${pi.toFixed(2)}`); // pi ≈ 3.14
Python
# Python f-string
user = {"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.14159
print(f"pi ≈ {pi:.2f}") # pi ≈ 3.14
# Any expression works
print(f"2 + 2 = {2 + 2}") # 2 + 2 = 4
TypeScript
# TypeScript
# 1. Compile and run
tsc hello.ts && node hello.js
# 2. Direct with ts-node
npx ts-node hello.ts
# 3. Via npm script (package.json)
npm start
Python
# Python
# 1. Direct — no compilation step
python3 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.hello

นี่คือ pattern ของ Python ที่ไม่มีตัวเทียบตรง ๆ ใน TypeScript จึงควรอธิบายให้ละเอียดสักหน่อย

เวลา Python รันไฟล์โดยตรงด้วย python3 hello.py interpreter จะตั้ง __name__ ของ module นั้นเป็น string "__main__" แต่ถ้าไฟล์อื่นเรียก import hello ค่า __name__ จะกลายเป็น "hello" ซึ่งก็คือชื่อ module แทน

ดังนั้น if __name__ == "__main__": จึงแปลว่า “รันโค้ดในนี้เฉพาะตอนไฟล์นี้เป็น entry point อย่าไปรันตอนโดน import”

TypeScript
// 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
# Python: the entry-point guard
def 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"))
# 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()
`console.log` ใน Python คืออะไร?
`__name__` มีค่าเป็นอะไรเมื่อรัน file โดยตรงด้วย `python3 hello.py`?
Python string prefix ไหนสร้างสิ่งเทียบเท่า template literal?
เกิดอะไรขึ้นกับ block `if __name__ == "__main__":` เมื่อ module อื่น import ไฟล์นี้?