以下我將針對 PHP 和 Python 在一些基本語法上的差異進行比較,希望能幫助你更快上手:
PHP 與 Python 基本語法差異比較
1. 變數 (Variables)
- PHP:
- 變數以
$
符號開頭。 - 不需要宣告變數類型,類型會自動推斷。
- 範例:
PHP
<?php $name = "Alice"; $age = 30; ?>
- 變數以
- Python:
- 變數不需要任何特殊符號開頭。
- 不需要宣告變數類型,類型會自動推斷。
- 範例:
Python
name = "Alice" age = 30
- 差異重點: Python 變數更簡潔,沒有
$
符號。
2. 語句結束符 (Statement Terminator)
- PHP:
- 每條語句通常以分號
;
結束。 - 範例:
PHP
<?php echo "Hello, world!"; $x = 10; ?>
- 每條語句通常以分號
- Python:
- 通常不需要分號
;
結束語句,換行即表示語句結束。 - 範例:
Python
print("Hello, world!") x = 10
- 通常不需要分號
- 差異重點: Python 更依賴換行來區分語句,減少了分號的使用。
3. 程式碼區塊 (Code Blocks)
- PHP:
- 使用大括號
{}
來定義程式碼區塊 (例如:函式、條件語句、迴圈)。 - 範例:
PHP
<?php if ($age > 18) { echo "成年"; } function greet($name) { echo "Hello, " . $name; } ?>
- 使用大括號
- Python:
- 使用縮排 (Indentation) 來定義程式碼區塊。這是 Python 最顯著的語法特點之一,必須嚴格遵守。
- 通常使用 4 個空格作為縮排。
- 範例:
Python
if age > 18: print("成年") def greet(name): print("Hello, " + name)
- 差異重點: 這是 PHP 和 Python 之間最大的語法差異。 PHP 使用
{}
,Python 則依賴嚴格的縮排。初學者需要特別注意這一點。
4. 輸出 (Output)
- PHP:
- 主要使用
echo
或print
。 - 範例:
PHP
<?php echo "My name is " . $name; print "My age is " . $age; ?>
- 主要使用
- Python:
- 主要使用
print()
函式。 - 範例:
Python
print("My name is " + name) print(f"My age is {age}") # 推薦使用 f-string
- 主要使用
- 差異重點: Python 使用
print()
函式,且推薦使用 f-string (格式化字串文字) 進行字串組合和變數嵌入,這比 PHP 的.
連接符更簡潔。
5. 註解 (Comments)
- PHP:
- 單行註解:
//
或#
- 多行註解:
/* ... */
- 範例:
PHP
<?php // 這是一行註解 # 這也是一行註解 /* * 這是多行註解 * 跨越多行 */ ?>
- 單行註解:
- Python:
- 單行註解:
#
- 多行註解 (通常使用三引號字串
"""..."""
或'''...'''
,雖然它實際上是字串字面量,但常被用作多行註解或 docstring)。 - 範例:
Python
# 這是一行註解 """ 這是多行註解 (docstring) 常用於函式或類的說明 """ ''' 這也是多行註解 '''
- 單行註解:
- 差異重點: 兩者單行註解相似,Python 的多行註解習慣使用三引號字串。
6. 運算子 (Operators)
- 算術運算子 (Arithmetic Operators): 大多數相同 (
+
,-
,*
,/
,%
)- PHP 獨有:
**
(指數運算) - Python 獨有:
//
(整數除法)- PHP
/
運算結果可以是浮點數,Python/
也是浮點數。 - PHP 整數除法需要
intdiv()
或(int)($a / $b)
。 - Python 的
//
會直接得到整數部分。
- PHP
- PHP 獨有:
- 字串連接 (String Concatenation):
- PHP: 使用
.
點號。PHP$greeting = "Hello" . " " . "World";
- Python: 使用
+
加號。Pythongreeting = "Hello" + " " + "World"
- Python 更推薦使用 f-string 或
join()
方法來進行字串連接,尤其是在多個字串時。
- Python 更推薦使用 f-string 或
- PHP: 使用
- 比較運算子 (Comparison Operators): 大多數相同 (
==
,!=
,>
,<
,>=
,<=
)- PHP 獨有:
===
(嚴格相等,比較值和類型),!==
(嚴格不相等)。 - Python: 沒有
===
,==
就會比較值。Python 的類型檢查通常在其他地方進行,或者透過設計模式避免此類問題。
- PHP 獨有:
- 邏輯運算子 (Logical Operators):
- PHP:
and
,or
,xor
,!
,&&
,||
- Python:
and
,or
,not
- 差異重點: Python 使用英文單字
and
,or
,not
,PHP 則同時支持英文單字和符號。
- 差異重點: Python 使用英文單字
- PHP:
7. 條件語句 (Conditional Statements)
- PHP (
if
,else if
,else
):PHP<?php if ($score >= 90) { echo "A"; } elseif ($score >= 80) { echo "B"; } else { echo "C"; } ?>
- Python (
if
,elif
,else
):Pythonif score >= 90: print("A") elif score >= 80: print("B") else: print("C")
- 差異重點: Python 使用
elif
而非else if
,且程式碼區塊由縮排定義。
8. 迴圈 (Loops)
for
迴圈:- PHP (
for
): 傳統的 C 語言風格for
迴圈。PHP<?php for ($i = 0; $i < 5; $i++) { echo $i; } ?>
- Python (
for ... in
): 迭代器風格的for
迴圈,通常用於遍歷序列 (如列表、元組、字串) 或可迭代對象。Pythonfor i in range(5): # range(5) 生成 0 到 4 的序列 print(i) my_list = ["apple", "banana", "cherry"] for item in my_list: print(item)
- PHP (
foreach
/for ... in
迴圈:- PHP (
foreach
): 遍歷陣列和物件。PHP<?php $colors = ["red", "green", "blue"]; foreach ($colors as $color) { echo $color; } ?>
- Python (
for ... in
): Python 的for ... in
本身就相當於 PHP 的foreach
。Pythoncolors = ["red", "green", "blue"] for color in colors: print(color)
- PHP (
while
迴圈: 兩者語法非常相似,主要差別在於區塊定義方式。- PHP:
PHP
<?php $count = 0; while ($count < 5) { echo $count; $count++; } ?>
- Python:
Python
count = 0 while count < 5: print(count) count += 1 # Python 中通常使用 +=, -= 等簡寫運算子
- PHP:
- 差異重點: Python 的
for
迴圈更注重迭代,沒有傳統的 C 風格for
迴圈。
9. 陣列 (Arrays) / 列表 (Lists)
- PHP:
- 陣列是高度彈性的,可以同時作為索引陣列和關聯陣列 (字典)。
- 範例:
PHP
<?php $fruits = ["apple", "banana", "cherry"]; // 索引陣列 $person = ["name" => "Bob", "age" => 25]; // 關聯陣列 ?>
- Python:
- 列表 (List): 有序、可變的集合,類似 PHP 的索引陣列。
Python
fruits = ["apple", "banana", "cherry"]
- 字典 (Dictionary): 無序、可變的鍵值對集合,類似 PHP 的關聯陣列。
Python
person = {"name": "Bob", "age": 25}
- 列表 (List): 有序、可變的集合,類似 PHP 的索引陣列。
- 差異重點: Python 區分列表 (List) 和字典 (Dictionary),而 PHP 的陣列則包含了兩者的功能。Python 的列表和字典有自己特定的語法和方法。
10. 函式 (Functions)
- PHP:
- 使用
function
關鍵字定義。 - 函式參數可以有類型提示 (PHP 7+)。
- 函式返回值可以有類型提示 (PHP 7+)。
- 範例:
PHP
<?php function add($a, $b): int { return $a + $b; } ?>
- 使用
- Python:
- 使用
def
關鍵字定義。 - 函式參數和返回值可以有類型提示 (Python 3.5+),但這些是提示 (hint),而不是強制執行。
- 範例:
Python
def add(a: int, b: int) -> int: return a + b
- 使用
- 差異重點: 關鍵字不同 (
function
vsdef
),Python 函式定義結尾有冒號:
。
11. 引入檔案 (Including Files)
- PHP:
include
,require
,include_once
,require_once
。- 範例:
PHP
<?php include 'header.php'; require_once 'config.php'; ?>
- Python:
- 使用
import
語句引入模組 (module)。 - 範例:
Python
import math from my_module import my_function
- 使用
- 差異重點: Python 採用模組化的概念,使用
import
。
學習建議:
- 習慣縮排 (Indentation): 這是從 PHP 轉向 Python 最需要適應的地方。養成良好的縮排習慣是寫出可運行 Python 程式的基礎。
- 理解 Python 的資料結構: PHP 的陣列非常強大,但 Python 將其拆分為列表 (list)、元組 (tuple)、字典 (dictionary) 和集合 (set),每種都有其特定的用途。理解它們的差異和使用場景非常重要。
- 多寫程式碼: 實際動手寫 Python 程式是最好的學習方式。從簡單的程式開始,逐漸增加複雜度。
- 善用資源:
- 官方文件: Python 官方文件非常詳細且易於理解。
- 線上教學: Codecademy, FreeCodeCamp, Coursera 等都有很好的 Python 課程。
- 書籍: 許多優秀的 Python 入門書籍可以參考。
- 社群: Stack Overflow, 各種 Python 論壇都可以找到幫助。
- 認識 Python 的生態系: Python 在科學計算、網路爬蟲、機器學習、Web 開發 (Django, Flask) 等領域都有非常豐富的庫和框架。一旦掌握了基本語法,就可以探索這些領域。
詳細比較 PHP 和 Python 的 while
迴圈。
while
迴圈在兩種語言中的基本概念是相同的:只要給定的條件為真 (true),就重複執行一段程式碼。主要的差異體現在語法結構和區塊定義上。
PHP 的 while
迴圈
在 PHP 中,while
迴圈的語法結構如下:
<?php
while (條件表達式) {
// 當條件為真時,要執行的程式碼區塊
// 這裡通常會有一個改變條件表達式的語句,以避免無限迴圈
}
?>
特點:
- 關鍵字:
while
- 條件: 條件表達式放在小括號
()
內。 - 程式碼區塊: 使用大括號
{}
定義迴圈體。 - 語句結束符: 迴圈體內的每條語句通常以分號
;
結束。
範例:
計算從 0 到 4 的數字並印出:
<?php
$count = 0; // 初始化計數器變數
while ($count < 5) { // 當 $count 小於 5 時,迴圈繼續
echo "Current count: " . $count . "<br>"; // 印出當前計數
$count++; // 每次迴圈後,將 $count 遞增 1
}
echo "Loop finished. Final count: " . $count . "<br>"; // 迴圈結束後的訊息
?>
輸出:
Current count: 0
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Loop finished. Final count: 5
Python 的 while
迴圈
在 Python 中,while
迴圈的語法結構如下:
while 條件表達式:
# 當條件為真時,要執行的程式碼區塊
# 這裡通常會有一個改變條件表達式的語句,以避免無限迴圈
特點:
- 關鍵字:
while
- 條件: 條件表達式不需要小括號
()
。 - 冒號: 條件表達式後必須跟隨一個冒號
:
。 - 程式碼區塊: 使用嚴格的縮排來定義迴圈體。通常建議使用 4 個空格作為縮排。
- 語句結束符: 不需要分號
;
。
範例:
計算從 0 到 4 的數字並印出:
count = 0 # 初始化計數器變數
while count < 5: # 當 count 小於 5 時,迴圈繼續
print(f"Current count: {count}") # 印出當前計數 (使用 f-string)
count += 1 # 每次迴圈後,將 count 遞增 1 (常用 += 運算子)
print(f"Loop finished. Final count: {count}") # 迴圈結束後的訊息
輸出:
Current count: 0
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Loop finished. Final count: 5
關鍵差異總結
特點 | PHP while 迴圈 | Python while 迴圈 |
條件包裹 | (條件表達式) | 條件表達式 (無括號) |
迴圈體開頭 | { | : |
迴圈體定義 | 大括號 {} | 嚴格縮排 (Indentation) |
語句結束符 | ; (通常需要) | (不需要) |
變數符號 | $變數名 | 變數名 |
遞增/遞減 | ++ , -- (或 += , -= ) | += , -= (沒有 ++ , -- ) |
從 PHP 到 Python 的注意事項:
- 縮排是語法的一部分! 在 Python 中,如果縮排錯誤,你的程式碼將會產生
IndentationError
。這是 Python 強制程式碼風格一致性的方式。 - 變數沒有
$
: 在 Python 中,直接使用變數名即可。 - 沒有
++
和--
運算子: Python 沒有 C 家族語言中常見的++
和--
運算子。請使用+= 1
或count = count + 1
來進行遞增。 print()
函式: 記得在 Python 中使用print()
函式來輸出。- f-string (Python 3.6+): 推薦使用 f-string 來組合字串和變數,它比 PHP 的
.
連接符更為簡潔和可讀。
總體而言,while
迴圈的概念在兩種語言中非常相似,你只需要適應 Python 特有的語法結構(尤其是縮排和冒號)即可。多加練習,你會很快習慣的!
PHP 和 Python 中的「模組」概念,以及它們在功能和使用上的差異。
雖然兩者都有類似於「引入外部程式碼」的機制,但 Python 的「模組 (Module)」概念更加核心和結構化,是其程式碼組織的重要方式。
PHP 中的「模組」概念 (Files & Includes)
在 PHP 中,雖然沒有一個直接叫做「模組」的內建關鍵字或嚴格定義,但你可以透過檔案包含 (File Inclusion) 的方式來實現類似模組的功能,將程式碼組織成多個檔案,並在需要時引入。
PHP 主要使用以下語句來引入其他 PHP 檔案:
include 'filename.php';
require 'filename.php';
include_once 'filename.php';
require_once 'filename.php';
PHP 檔案包含的特點:
- 行為方式: 當你
include
或require
一個檔案時,被引入檔案的內容會被直接插入到引入點。這就像你把那個檔案的內容複製貼上到當前檔案一樣。 - 變數作用域: 被引入檔案中的程式碼會繼承引入點的變數作用域。這意味著被引入的檔案可以存取引入它的檔案中的變數。
- 錯誤處理:
include
:如果檔案不存在或有錯誤,會發出警告 (Warning),但腳本會繼續執行。require
:如果檔案不存在或有錯誤,會發出致命錯誤 (Fatal Error),導致腳本停止執行。_once
後綴:確保文件只被引入一次,即使在程式碼中被多次指定。這在避免函式或類重複定義時很有用。
- 用途: 常用於分解大型程式碼、重複使用的函式庫、配置檔案、模板檔案 (如 header.php, footer.php) 等。
PHP 範例:
utils.php
檔案:
<?php
// utils.php
function greet($name) {
return "Hello, " . $name . "!";
}
$PI = 3.14159;
?>
main.php
檔案:
<?php
// main.php
require_once 'utils.php'; // 引入 utils.php
echo greet("Alice") . "<br>"; // 使用 utils.php 中的函式
echo "The value of PI is: " . $PI . "<br>"; // 存取 utils.php 中的變數
?>
Python 中的「模組 (Module)」概念
在 Python 中,「模組」是一個更為正式和內建的概念。一個 Python 模組就是一個包含 Python 定義和語句的 .py
檔案。
當你 import
一個模組時,Python 會執行那個模組的程式碼,並將其中定義的所有物件(函式、類、變數等)載入到一個命名空間中,供你使用。
Python 模組的特點:
- 檔案即模組: 任何一個
.py
檔案都可以被視為一個模組。 - 命名空間: 每個模組都有自己的獨立命名空間。當你導入一個模組時,你需要透過模組名來存取其中的成員 (例如
module_name.function_name
)。這有助於避免命名衝突。 - 只執行一次: 模組在一個程式運行中只會被導入和執行一次。即使你多次
import
同一個模組,它也只會被載入一次。 import
語句:import module_name
: 導入整個模組。import module_name as alias
: 導入整個模組並給它一個別名。from module_name import specific_item
: 只導入模組中的特定函式、類或變數。from module_name import *
: 導入模組中的所有公開成員(不推薦,可能導致命名衝突)。
- 用途: 組織程式碼、提供可重用的函式和類、建立函式庫、管理專案結構等。
Python 範例:
my_utils.py
檔案:
# my_utils.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
class Calculator:
def add(self, a, b):
return a + b
main.py
檔案:
# main.py
# 方式一:導入整個模組
import my_utils
print(my_utils.greet("Bob")) # 透過模組名存取
print(f"The value of PI is: {my_utils.PI}")
calc = my_utils.Calculator()
print(f"2 + 3 = {calc.add(2, 3)}")
# 方式二:只導入特定成員
from my_utils import greet, PI
print(greet("Charlie")) # 直接存取
print(f"PI again: {PI}")
# 方式三:導入模組並給它別名
import my_utils as mu
print(mu.greet("David"))
PHP 檔案包含 與 Python 模組 的主要差異
特點 | PHP (include/require) | Python (import) |
概念 | 檔案包含 (Code Inclusion) | 模組化 (Modular Programming) |
命名空間 | 被引入的程式碼通常在引入點的相同作用域執行。 | 每個模組有獨立的命名空間。需要透過模組名 (module.item ) 存取成員。 |
重複導入 | 默認會重複執行和定義,需用 _once 避免。 | 自動處理,一個模組在一次運行中只會被執行和載入一次。 |
錯誤處理 | include 警告,require 致命錯誤。 | ModuleNotFoundError (找不到模組),其他錯誤會直接拋出。 |
推薦用法 | 常用於分解網頁元件、配置檔案。 | 核心的程式碼組織方式,用於封裝功能、建立函式庫。 |
物件導向性 | 較鬆散,更多是文件層級的引入。 | 更強調物件導向和邏輯上的單元劃分。 |
總結與學習建議
- Python 的模組是其程式碼組織的基石。 理解模組和命名空間的概念對於編寫可維護和可擴展的 Python 程式至關重要。
- 從 PHP 的檔案包含過渡到 Python 的模組,你會發現 Python 鼓勵更清晰的程式碼分離和更好的命名空間管理,這有助於避免全局變數的濫用和命名衝突。
- 當你在 Python 中寫一個
.py
檔案,並且裡面定義了一些函式、類或變數,那麼這個檔案本身就已經是一個模組了,你可以直接在其他 Python 檔案中import
它。 - Python 還有更進階的「包 (Package)」概念,它是一個包含多個模組的目錄,用於組織更大型的專案。
函式通常涉及字串操作、陣列/列表操作、數學運算、檔案操作等。我們來逐一比較。
PHP 與 Python 常用函式比較
1. 字串操作 (String Manipulation)
功能 | PHP 函式/操作 | Python 函式/操作 | 備註 |
長度 | strlen($str) | len(str_var) | Python 使用內建的 len() 函式。 |
連接 | . 運算子 ($s1 . $s2 ) | + 運算子 (s1 + s2 ) 或 f-string | Python 推薦 f-string (f"{s1}{s2}" ) 或 str.join() 。 |
取子字串 | substr($str, $start, $length) | str_var[start:end] (切片) | Python 切片操作非常強大,end 是不包含的索引。 |
替換 | str_replace($search, $replace, $str) | str_var.replace(old, new) | Python 的 replace() 返回新字串,原字串不變。 |
尋找 | strpos($haystack, $needle) | str_var.find(substring) | PHP 返回位置或 false ;Python 返回位置或 -1 。 |
分割 | explode($delimiter, $str) | str_var.split(delimiter) | 返回字串列表。 |
轉大小寫 | strtolower($str) , strtoupper($str) | str_var.lower() , str_var.upper() | Python 字串方法直接作用於字串物件。 |
去除空白 | trim($str) , ltrim($str) , rtrim($str) | str_var.strip() , str_var.lstrip() , str_var.rstrip() | |
檢查開頭 | str_starts_with($haystack, $needle) (PHP 8+) | str_var.startswith(prefix) | PHP 7.x 之前需要自定義或使用 strpos 。 |
檢查結尾 | str_ends_with($haystack, $needle) (PHP 8+) | str_var.endswith(suffix) | PHP 7.x 之前需要自定義或使用 substr 。 |
範例:
<?php
// PHP 字串操作
$text = " Hello World! ";
echo strlen($text) . "\n"; // 16
echo trim($text) . "\n"; // "Hello World!"
echo str_replace("World", "Python", $text) . "\n"; // " Hello Python! "
$parts = explode(" ", trim($text)); // ["Hello", "World!"]
echo $parts[0] . "\n";
?>
# Python 字串操作
text = " Hello World! "
print(len(text)) # 16
print(text.strip()) # "Hello World!"
print(text.replace("World", "Python")) # " Hello Python! "
parts = text.strip().split(" ") # ["Hello", "World!"]
print(parts[0])
2. 陣列 (Arrays) / 列表 (Lists) / 字典 (Dictionaries) 操作
這是差異較大的部分,因為 PHP 的陣列多功能性被 Python 拆分為多個資料結構。
功能 | PHP 函式/操作 | Python 函式/操作 (列表 List) | Python 函式/操作 (字典 Dict) | 備註 |
建立 | [] 或 array() | [] | {} | Python 列表用 [] ,字典用 {} 。 |
長度 | count($arr) | len(list_var) | len(dict_var) | Python 統一使用 len() 。 |
新增元素 | $arr[] = $value 或 array_push($arr, $value) | list_var.append(value) | dict_var[key] = value | append 是列表方法。字典直接賦值。 |
刪除元素 | unset($arr[key]) 或 array_splice($arr, $offset, $length) | del list_var[index] 或 list_var.pop(index) | del dict_var[key] 或 dict_var.pop(key) | pop 也可以用於列表。 |
遍歷 | foreach ($arr as $key => $value) | for item in list_var: <br>for key, value in dict_var.items(): | for key in dict_var: 或 for value in dict_var.values(): | Python 的 for ... in 迴圈更為通用。 |
檢查存在 | in_array($value, $arr) (索引陣列)<br>array_key_exists($key, $arr) (關聯陣列) | value in list_var | key in dict_var | Python 使用 in 關鍵字。 |
排序 | sort() , rsort() , asort() , ksort() 等 | list_var.sort() 或 sorted(list_var) | sorted(dict_var.items()) (排序鍵值對) | Python 的 sort() 會原地修改,sorted() 返回新列表。 |
合併 | array_merge($arr1, $arr2) | list1 + list2 (產生新列表) | {**dict1, **dict2} (Python 3.5+ for dict) | 列表使用 + 或 extend() 。字典使用解包或 update() 。 |
取得所有鍵 | array_keys($arr) | list(dict_var.keys()) | list(dict_var.keys()) | Python 返回 dict_keys 物件,可轉為列表。 |
取得所有值 | array_values($arr) | list(dict_var.values()) | list(dict_var.values()) | Python 返回 dict_values 物件,可轉為列表。 |
範例:
<?php
// PHP 陣列操作
$numbers = [10, 20, 30];
$numbers[] = 40; // [10, 20, 30, 40]
echo count($numbers) . "\n"; // 4
if (in_array(20, $numbers)) { echo "Found 20!\n"; }
$person = ["name" => "Alice", "age" => 30];
echo $person["name"] . "\n";
if (array_key_exists("age", $person)) { echo "Age exists!\n"; }
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
# Python 列表和字典操作
numbers = [10, 20, 30]
numbers.append(40) # [10, 20, 30, 40]
print(len(numbers)) # 4
if 20 in numbers:
print("Found 20!")
person = {"name": "Alice", "age": 30}
print(person["name"])
if "age" in person:
print("Age exists!")
for key, value in person.items():
print(f"{key}: {value}")
3. 數學函式 (Mathematical Functions)
大多數基本的數學運算子 (+
, -
, *
, /
, %
) 在兩者中都相似。更複雜的數學函式通常需要引入模組。
功能 | PHP 函式/操作 | Python 函式/操作 (通常需要 import math) | 備註 |
取絕對值 | abs($num) | abs(num) | 內建函式。 |
四捨五入 | round($num, $precision) | round(num, ndigits) | 內建函式。 |
向上取整 | ceil($num) | math.ceil(num) | |
向下取整 | floor($num) | math.floor(num) | |
平方根 | sqrt($num) | math.sqrt(num) | |
冪次 | pow($base, $exp) 或 ** | math.pow(base, exp) 或 base ** exp | Python 的 ** 運算子更常用。 |
隨機數 | rand($min, $max) 或 mt_rand() | random.randint(min, max) (需 import random ) | Python 的 random 模組提供更多隨機數功能。 |
範例:
<?php
// PHP 數學函式
echo abs(-10) . "\n"; // 10
echo round(3.14159, 2) . "\n"; // 3.14
echo sqrt(25) . "\n"; // 5
?>
# Python 數學函式
import math
import random
print(abs(-10)) # 10
print(round(3.14159, 2)) # 3.14
print(math.sqrt(25)) # 5.0
print(random.randint(1, 10)) # 1 到 10 之間的隨機整數
4. 檔案系統操作 (File System Operations)
功能 | PHP 函式/操作 | Python 函式/操作 (通常需要 import os, import shutil) | 備註 |
讀取檔案內容 | file_get_contents($path) | with open(path, 'r') as f: content = f.read() | Python 推薦使用 with open(...) as f: 確保檔案正確關閉。 |
寫入檔案 | file_put_contents($path, $data) | with open(path, 'w') as f: f.write(data) | w 寫入 (覆蓋),a 追加。 |
判斷檔案是否存在 | file_exists($path) | os.path.exists(path) 或 pathlib.Path(path).exists() | pathlib 模組提供更物件導向的檔案路徑操作。 |
建立目錄 | mkdir($path) | os.makedirs(path) | Python 的 os.makedirs 可以創建多層目錄。 |
刪除檔案 | unlink($path) | os.remove(path) | |
刪除目錄 | rmdir($path) | os.rmdir(path) (空目錄)<br>shutil.rmtree(path) (非空目錄) | Python 區分空目錄和非空目錄的刪除。 |
範例:
<?php
// PHP 檔案操作
$filename = "test.txt";
file_put_contents($filename, "Hello from PHP!");
if (file_exists($filename)) {
echo file_get_contents($filename) . "\n";
unlink($filename);
}
?>
# Python 檔案操作
import os
filename = "test.txt"
with open(filename, 'w') as f:
f.write("Hello from Python!")
if os.path.exists(filename):
with open(filename, 'r') as f:
content = f.read()
print(content)
os.remove(filename)
5. 日期與時間 (Date and Time)
日期時間處理在兩種語言中都比較複雜,因為涉及到格式化、時區等。
功能 | PHP 函式/操作 | Python 函式/操作 (通常需要 import datetime) | 備註 |
取得當前時間 | time() (Unix timestamp)<br>date($format) | datetime.datetime.now() | Python 處理日期時間為 datetime 物件。 |
格式化時間 | date($format, $timestamp) | datetime_obj.strftime(format_string) | 格式化字串的代碼不同。 |
解析時間字串 | strtotime($time_string) | datetime.datetime.strptime(time_string, format) | PHP 的 strtotime 更為靈活。 |
範例:
<?php
// PHP 日期時間
echo date("Y-m-d H:i:s") . "\n"; // 當前日期時間
?>
# Python 日期時間
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
總結與學習策略
- 物件導向 vs. 函式化: Python 許多常用操作(特別是字串、列表)都是作為物件的方法來實現的(例如
str_var.lower()
),而不是像 PHP 那樣通常是獨立的函式(例如strtolower($str)
)。這反映了 Python 更強的物件導向特性。 len()
的通用性: 在 Python 中,len()
函式用於獲取許多不同類型(字串、列表、字典、元組、集合等)的長度,而 PHP 則有strlen()
和count()
。- 列表 vs. 陣列 vs. 字典: 再次強調,Python 區分列表和字典,這是你需要適應的關鍵點。特別是處理鍵值對時,Python 的字典有其專用的方法。
- 模組的引入: Python 許多常用功能都被組織在標準庫的模組中(如
math
,random
,os
,datetime
等),你需要先import
這些模組才能使用其中的函式。 with
語句: 在 Python 中進行檔案操作時,強烈建議使用with open(...) as f:
語句,它會自動處理檔案的開啟和關閉,即使發生錯誤也能確保資源被釋放。
沒有留言:
張貼留言