ไวยากรณ์ของ Python
บทความนี้อธิบายเกี่ยวกับไวยากรณ์ของภาษา Python
YouTube Video
ไวยากรณ์ใน Python
การย่อหน้า
Python ใช้การย่อหน้าเพื่อกำหนดบล็อกของโค้ด ไม่เหมือนกับภาษาอื่น ๆ ที่ใช้เครื่องหมายวงเล็บปีกกา {}
ในการระบุบล็อกโค้ด Python ใช้การย่อหน้าแทน โดยทั่วไปแล้วจะใช้การย่อหน้าด้วยการเว้นวรรค 4 ช่อง แต่การใช้แท็บก็สามารถทำได้ อย่างไรก็ตาม คุณควรระวังไม่ให้ผสมการเว้นวรรคและแท็บในไฟล์เดียวกัน
1x = 5
2if x > 0:
3 print("Positive")
4else:
5 print("Non-positive")
คอมเมนต์
ความคิดเห็นแบบบรรทัดเดียว
ใน Python คอมเมนต์จะเริ่มต้นด้วยเครื่องหมาย #
ทุกอย่างจนถึงสิ้นสุดบรรทัดจะถือว่าเป็นคอมเมนต์
1# This is a comment
2print("Hello, World!") # This is also a comment
สตริงเอกสาร (Docstring
)
docstring
เป็นสตริงที่ใช้สำหรับอธิบายโค้ด โดยล้อมรอบด้วยเครื่องหมายอัญประกาศสามครั้ง """
หรืออัญประกาศเดี่ยวสามครั้ง '''
โดยปกติใช้สำหรับอธิบายโมดูล คลาส และฟังก์ชัน
1def greet(name):
2 """
3 This function displays a greeting to the specified name.
4
5 Parameters:
6 name (str): The name of the person to greet.
7 """
8 print(f"Hello, {name}!")
สามารถดู Docstring
ได้โดยใช้ฟังก์ชัน help()
1help(greet)
แนวทางปฏิบัติที่ดีที่สุดสำหรับความคิดเห็น
แนวทางปฏิบัติที่ดีที่สุดสำหรับความคิดเห็นมีดังต่อไปนี้:
1# Good example
2# Validate user input and display a personalized message
3
4# Ask for the user's name
5name = input("Enter your name: ")
6
7# Ask for the user's age and convert it to an integer
8age = int(input("Enter your age: "))
9
10# Check eligibility based on age
11if age >= 18:
12 # Inform the user that they can register
13 print(f"Welcome, {name}! You are eligible to register.")
14else:
15 # Inform the user that they are underage
16 print(f"Sorry, {name}. You must be at least 18 years old to register.")
17
18# Bad example
19# Store the user's name in the variable 'name'
20name = input("Enter your name: ")
21
22# Convert the input to an integer and store it in 'age'
23age = int(input("Enter your age: "))
24
25# Check if the user is greater than or equal to 18
26if age >= 18:
27 # Print a welcome message
28 print(f"Welcome, {name}! You are eligible to register.")
29else:
30 # Print a rejection message
31 print(f"Sorry, {name}. You must be at least 18 years old to register.")
-
ชัดเจนและกระชับ ความคิดเห็นถูกใช้เพื่ออธิบายเจตนาของโค้ดอย่างชัดเจน
-
อย่าพูดถึงความหมายของโค้ดซ้ำ หลีกเลี่ยงการเขียนความคิดเห็นบนโค้ดที่สามารถเข้าใจได้ด้วยตนเอง
-
รักษาความสม่ำเสมอ ในงานพัฒนาทีม สิ่งสำคัญคือการรักษาความเสมอต้นเสมอปลายของรูปแบบและสไตล์ของความคิดเห็น
ตัวแปรและประเภทข้อมูล
ใน Python คุณไม่จำเป็นต้องระบุประเภทเมื่อประกาศตัวแปร ประเภทของข้อมูลจะกำหนดโดยอัตโนมัติเมื่อมีการกำหนดค่า
1x = 10 # Integer
2y = 3.14 # Floating-point number
3name = "Alice" # String (text)
4is_active = True # Boolean value (True or False)
คำสั่งเงื่อนไข
คำสั่งเงื่อนไขใช้ if
, elif
(else if) และ else
1x = 0
2if x > 0:
3 print("Positive")
4elif x == 0:
5 print("Zero")
6else:
7 print("Negative")
คำสั่งวนซ้ำ
Python มีคำสั่งวนซ้ำ for
และ while
ซึ่งแต่ละคำสั่งใช้งานในลักษณะที่แตกต่างกัน
คำสั่ง for
คำสั่ง for
มักใช้สำหรับวนซ้ำผ่านองค์ประกอบของรายการหรือตูเปิล
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)
คำสั่ง while
คำสั่ง while
จะทำซ้ำลูปตราบใดที่เงื่อนไขเป็นจริง
1count = 0
2while count < 5:
3 print(count)
4 count += 1
การกำหนดฟังก์ชัน
ใน Python ฟังก์ชันถูกกำหนดโดยใช้คีย์เวิร์ด def
1def greet(name):
2 print(f"Hello, {name}!")
3
4greet("Alice")
การกำหนดคลาส
ใน Python คุณสามารถกำหนดคลาสโดยใช้คีย์เวิร์ด class
เพื่อเปิดใช้งานการเขียนโปรแกรมเชิงวัตถุ
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5 def bark(self):
6 print("Woof!")
7
8dog = Dog("Fido")
9dog.bark()
โมดูลและการนำเข้า
ใน Python คำสั่ง import
ใช้สำหรับนำเข้าโมดูลและเข้าถึงโค้ดที่มีอยู่แล้ว
1# Importing the sqrt function from the math module
2from math import sqrt
3
4result = sqrt(16)
5print(result) # Output: 4.0
ข้อผิดพลาดและการจัดการข้อยกเว้น
โครงสร้าง try-except
ของ Python ใช้สำหรับจัดการข้อผิดพลาดและสถานการณ์ที่ไม่คาดคิด
1# Catching a division-by-zero error example
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("Cannot divide by zero.")
สรุป
ไวยากรณ์พื้นฐานของ Python นั้นง่ายมากและอ่านเข้าใจได้ง่าย พื้นฐานเหล่านี้เป็นส่วนสำคัญสำหรับการเขียนโค้ด Python
คุณสามารถติดตามบทความข้างต้นโดยใช้ Visual Studio Code บนช่อง YouTube ของเรา กรุณาตรวจสอบช่อง YouTube ด้วย