【Python】學習筆記:異常處理is_number()

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False
 
# 測試字符串和數字
print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True
 
# 測試 Unicode
# 阿拉伯語 5
print(is_number('٥'))  # True
# 泰語 2
print(is_number('๒'))  # True
# 中文數字
print(is_number('四')) # True
# 版權號
print(is_number('©'))  # False

代碼來源:菜鳥教程https://www.runoob.com/python3/python3-check-is-number.html

這段  判斷字符串是否爲數字  的代碼真的是讓老陌眼前一亮,之前測試is_number()我最多就能想到一些簡單的字母,雖然也是利用了unicode的一些規則吧,但是我明顯忽略了它包羅萬象的庫,所以在看到阿拉伯語、泰語的時候真的有種驚喜的感覺!回過頭來看函數的定義,真的覺得下面這幾行太美妙了! 

import unicodedata
        unicodedata.numeric(s)
        return True

然後再看外面套着的異常處理,第一次看到 try-except 還真是有點不太習慣呢,畢竟在java裏面我看到的更多的是try-catch,不過轉念一想,通常catch後面跟的都是各種Exception,所以“精簡”一下變成try-except也就覺得挺好理解的了~

後來,老陌趁機複習了一下,我發現python有別於之前接觸過的一些語言,它在觸發/拋出異常時使用的關鍵字是raise,這個真的是不同於JAVA和PHP的,所以這裏老陌覺得需要特別注意一下!(其實後來想想也就是說法不同吧,感覺這就和當初學習“函數”和“方法”是一個意思)。

import java.io.*;
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}
<?php
// 創建一個有異常處理的函數
function checkNum($number)
{
    if($number>1)
    {
        throw new Exception("變量值必須小於等於 1");
    }
        return true;
}
    
// 在 try 塊 觸發異常
try
{
    checkNum(2);
    // 如果拋出異常,以下文本不會輸出
    echo '如果輸出該內容,說明 $number 變量';
}
// 捕獲異常
catch(Exception $e)
{
    echo 'Message: ' .$e->getMessage();
}
?>
def functionName( level ):
    if level < 1:
        raise Exception("Invalid level!", level)
        # 觸發異常後,後面的代碼就不會再執行

參考資料:菜鳥教程-Python異常處理https://www.runoob.com/python/python-exceptions.html

菜鳥教程-Java異常處理https://www.runoob.com/java/java-exceptions.html

菜鳥教程-PHP異常處理https://www.runoob.com/php/php-exception.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章