Python基礎篇-複習1

2024/04/10 Python

你想了解Python的基本概念嗎?本文介紹了Python的基本語法和數據類型。首先,Python的縮排非常重要,用於判定代碼塊的範圍。Python有兩個主要版本:Python2和Python3,它們之間有顯著差異。變量不需要定義數據類型,可以通過簡單賦值來使用。Python支持多種基本數據類型,如整數、浮點數、布爾值和字符串。字符串可以通過轉義字符進行處理,也有多種格式化方法。列表是一種常用的數據結構,支持合並、添加、刪除和排序等操作。運算符和注釋在代碼中也很重要,單行注釋使用#,多行注釋則使用docstrings。通過這些基本概念的掌握,你可以開始用Python進行編程。

Python基礎篇-複習1

  1. 事前常識
    • 官網
    • 教學
    • 縮排很重要,基本上用縮排來判斷程式區塊範圍
    • python2和python3有明顯差異
  2. 基本語法
    1. 變數宣告
      • 不需要定義數據類型 ```python=1 numA = 3 numB = 3.14 stringC = “3.14” tupleD, =(3.14,) #不可修改 listD = [3.14] dictE = {“num”:3.14} setF = {}

      ```

    2. 全域變數與區域變數
      • 根據縮排區塊去判斷個別變數的性質
    3. 基本數據類型
      • number
          4        # int
          3.14     # float
          0b1111 # 15 ( 二進制 )
          0o1111 # 585 ( 八進制 )
          0x1111 # 4369 ( 十六進制 )
        
      • bool
        • False or True
        • bool(x):x=0 為 False,other 為True
      • string
        • ”” or ‘‘包住
        • offset,slice
        • 轉義
          • 轉義字元 說明  
            ( 放在一行結尾 ) 接續下一行  
            \ 顯示反斜線  
            ' 顯示單引號  
            " 顯示雙引號  
            \b 刪除前一個字元  
            \n 換行  
            \t tab 鍵  
        • 前方加上 r 代表不轉義
          • r’\n’
        • 常用函數
          • len(),split(),replace(),strip()
          • sub in str,find(),startswith(),endswith(),count()
          • isalnum(),isalpha(),isdigit(),islower(),isupper(),istitle()
          • title(),upper(),lower(),swapcase()
        • 格式化
          • %, .format, f-string
      • list
        • 合併串列 +,extend
        • offset,slice
        • 添加串列項目 append,insert
        • 刪除串列項目 del,remove,pop,clear
        • 常用操作方法
          • 排序 a.sort(reverse=True)、 b=sorted(a)
          • 反轉 b = a[::-1]
          • 複製
            • slice、copy()、list() 數據會跟隨複製對象改變
            • deepcopy()
          • 取得項目offset index()
          • 取得串列長度 len()
          • 計算內容出現次數 count()
          • 結合串列內容 join()
          • in 檢查內容是否存在
          • 比較串列
            • 「==」、「!=」,可以比較兩個串列是否相等
            • 大於小於符號「<」、「<=」、「>=」、「>」,可以比較串列的長度
            • 只能針對「同樣型別」的資料
          • *號重複項目
    4. 運算符
    5. 註解
      • 單行註解 使用#
      • 多行註解
        • 沒有多行註解,請使用docstrings
            """
            This is a multi-line comment with docstrings
            print("Hello world")
            """
            print("Hello campers")
          

Search

    Table of Contents