初識Python,第一個小程序,判斷電話號碼


  • 編寫代碼的一般步驟
    • 明確需求
    • 理解需求
    • 對問題進行概括
    • 編寫代碼
    • 測試調試代碼
  • 需求
    • 輸入一串字符串 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
    • 把電話號碼(415-555-1011,415-555-9999)提取出來
  • 判斷電話號碼究竟是什么格式,考慮一下它的規律:只有數字和‘-’兩種字符,而且第三位和第七位一定是‘-’,這個時候考慮用數據驅動方式來寫;
  • 代碼如下
     1 #coding:utf-8
     2 #__author__ = 'Diva'
     3 
     4 PHONE_NUMBER_SIZE = 12  # 定義全局變量,電話號碼的長度
     5 
     6 def is_digital(ch):     # 判斷是否是數字
     7     if ord(ch) >= ord('0') and ord(ch) <= ord('9'):
     8         return True
     9     return False
    10 
    11 def is_special(ch):     # 判斷是否是‘-’
    12     if ord(ch) == ord('-'):
    13         return True
    14     return False
    15 
    16 def is_phone_number_check(chars):   # 判斷格式
    17     if len(chars) != PHONE_NUMBER_SIZE:
    18         return False
    19 
    20     for i in range(PHONE_NUMBER_SIZE):
    21         if not is_digital(chars[i]) and not is_special(chars[i]):   # 不是數字或者‘-’的退出
    22             return False
    23         if (i == 3 or i == 7) and not is_special(chars[i]):     # 第三位和第七位不是‘-’的退出
    24             return False
    25         if (i != 3 and i != 7) and not is_digital(chars[i]):    # 排除第三和第七,如果不是數字退出
    26             return False
    27     return True
    28 
    29 def split_phone_number(message):    #  篩選出號碼,進行判斷
    30     for n in range(len(message)):
    31         chars = message[n:n + PHONE_NUMBER_SIZE]
    32         if is_phone_number_check(chars):
    33             print('找到電話號碼為:' + chars)
    34     print('Done.')
    35 
    36 if __name__ == '__main__':
    37     message = 'Call me at 415-555-1011 tomorrow. 415-555-9999  is my office.'
    38     split_phone_number(message)

    # 最好是用戶什么都不需要做,只要把參數傳進去就好了;函數本來就有隱藏實現的作用:main 函數里只要把 message 傳進去就可以知道結果
  • 測試結果
  •  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM