Python 語法
本文將解釋 Python 的語法。
YouTube Video
Python 的語法
縮排
Python 使用縮排來定義代碼區塊。與許多其他使用大括號 {} 定義代碼區塊的語言不同,Python 使用縮排。通常使用四個空格進行縮排,但也可以使用 Tab 鍵。但請注意,不要在同一文件中混合使用空格和 Tab 鍵。
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}!")可以使用 help() 函數查看 Docstring。
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錯誤與異常處理
Python 的 try-except 結構用於處理錯誤和未預期的情況。
1# Catching a division-by-zero error example
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("Cannot divide by zero.")結論
Python 的基本語法非常簡單且易讀性高。這些基礎是撰寫 Python 代碼的重要要素。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。