ใช้ Editor ใดๆ ที่รองรับ Python (VS Code, PyCharm, Sublime Text, IDLE, ฯลฯ) Python มาพร้อม IDLE (Integrated Development and Learning Environment) แล้ว
ขั้นตอนด้วย IDLE
- เปิด IDLE
- File → New File (Ctrl+N)
- พิมพ์โค้ด:
print("Hello World!")
- Save:
hello.py(File → Save) - Run: Run → Run Module (F5)
รันจาก Command Line
c:\Users> python hello.py Hello World!
โครงสร้างไฟล์ Python (.py)
# hello.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""My first Python program"""
def main():
print("Hello World!")
if __name__ == "__main__":
main()
Best Practices:
- ใช้ Shebang
#!/usr/bin/env python3สำหรับ Unix/Linux/macOS - ระบุ Encoding
# -*- coding: utf-8 -*- - ใส่ Docstring อธิบายโปรแกรม
- ใช้
if __name__ == "__main__":เพื่อให้ import ได้โดยไม่รัน