Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเขียนโปรแกรม Python แรก (Hello World)

ใช้ Editor ใดๆ ที่รองรับ Python (VS Code, PyCharm, Sublime Text, IDLE, ฯลฯ) Python มาพร้อม IDLE (Integrated Development and Learning Environment) แล้ว

ขั้นตอนด้วย IDLE

  1. เปิด IDLE
  2. File → New File (Ctrl+N)
  3. พิมพ์โค้ด:
print("Hello World!")
  1. Save: hello.py (File → Save)
  2. 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 ได้โดยไม่รัน