1. Lambda 函數
lambda 函數是 Python 中的一個小的匿名函數。它可以接受多個參數,但僅限於單個表達式。Lambda 函數通常用於短期任務,並且以單行編寫。
Lambda 參數:表達式
# Adding 10 to a number
number = lambda num: num + 10
print(number(5)) # Output: 15
# Multiplying two numbers
x = lambda a, b: a * b
print(x(5, 6)) # Output: 30
異常處理
異常處理可確保您的程序在發生錯誤時不會崩潰。Python 允許您正常處理錯誤並繼續運行程序,而不是突然停止。
異常處理的關鍵組件:
- try:測試代碼塊是否有錯誤。
- except:如果發生錯誤,則處理錯誤。
- else:如果沒有錯誤,則執行代碼。
- finally:無論是否發生錯誤,都執行代碼。
示例:基本異常處理
try:
print(x) # 'x' is not defined
except:
print("An exception occurred") # Output: An exception occurred
例:處理特定錯誤
try:
print(x)
except NameError:
print("Variable x is not defined") # Output if NameError occurs
except:
print("Something else went wrong") # Output for other errors
示例:使用else
else 塊僅在 try 塊中沒有發生錯誤時運行。
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong") # Output: Nothing went wrong
示例:使用finally
finally 塊無論如何都會運行。
try:
print(x) # 'x' is not defined
except:
print("Something went wrong")
finally:
print("The 'try except' block is finished") # Always executes
文件處理
文件處理允許您在 Python 中創建、讀取、寫入、附加和刪除文件。
使用open()打開文件
open() 函數用於處理文件。它需要兩個參數:
- 文件名:文件的名稱。
- 模式:指定用途(讀取、寫入等)。
文件模式:
- r:讀取模式(如果文件不存在,則出錯)。
- a:附加模式(如果文件不存在,則創建文件)。
- w:寫入模式(如果文件不存在,則創建文件)。
- x:創建模式(如果文件已存在,則出錯)。
示例:讀取文件
file = open("textfile.txt", "r")
print(file.read())
file.close() # Always close the file after working with it
例:追加到文件
file = open("textfile.txt", "a")
file.write("Now the file has more content!")
file.close()
# Reading the updated file
file = open("textfile.txt", "r")
print(file.read())
示例:刪除文件
要刪除文件,您需要 os 模塊。
import os
# Deleting a file
os.remove("textfile.txt")
要點:
- 使用 file.close() 處理文件後,始終關閉文件。
- 可以使用異常處理來管理文件處理錯誤,以實現更順暢的工作流程。