1. 程式人生 > >python 從入門到實踐 ---基礎篇筆記

python 從入門到實踐 ---基礎篇筆記

python基礎入門

第一部分 基礎知識

第 1 章 運行第一個程序 打印消息 “Hello world!” 。
第 2 章 變量中存儲信息以及如何使用文本和數字。
第 3 4 章 列表 使用列表能夠在一個變量中存儲任意數量的信息,從而高效地處理數據:只需幾行代碼,你就能夠處理數百、數千乃至數百萬個值。
第 5 章 if 條件判斷
第 6 章 使用 Python 字典,將不同的信息關聯起來。與列表一樣,你也可以根據需要在字典中存儲任意數量的信息。
第 7 章 交互式程序 while 循環
第 8 章 函數。函數是執行特定任務的被命名的代碼塊
第 9 章 類,它讓你能夠模擬實物,如小狗、小貓、人、汽車、火箭等,讓你的代碼能夠表示任何真實或抽象的東西。

第 10 章 如何使用文件,以及如何處理錯誤以免程序意外地崩潰。你需要在程序關閉前保存數據,並在程序再次運行時讀取它們。你將學習 Python 異常,它們讓你能夠未雨綢繆,從而讓程序妥善地處理錯誤。
第 11 章為代碼編寫測試,以核實程序是否像你期望的那樣工作。這樣,擴展程序時,你就不用擔心引入新的 bug 。要想脫離初級程序員的陣容,躋身於中級程序員的行列,測試代碼是你必須掌握的基本技能之一。

第一章 第一個python程序

[root@localhost ~/python]# python   #進入python2.7交互式界面  相關版本以及提示信息
Python 2.7.5 (default, Aug  4 2017, 00:39:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello Python World")     #也可將代碼保存在文件中中使用python命令運行 .py文件
Hello Python World

第二章 變量以及簡單數據類型:字符串 數字

2.1變量命名規範

  • 1.變量名只能包含字母、數字和下劃線。變量名可以字母或下劃線打頭,但不能以數字打頭,例如,可將變量命名為 message_1 ,但不能將其命名為 1_message 。
  • 2.變量名不能包含空格,但可使用下劃線來分隔其中的單詞。例如,變量名 greeting_message 可行,但變量名 greeting message 會引發錯誤。
  • 3.不要將 Python 關鍵字和函數名用作變量名,即不要使用 Python 保留用於特殊用途的單詞,如 print (請參見附錄 A.4 )。
  • 4.變量名應既簡短又具有描述性。例如, name 比 n 好, student_name 比 s_n 好, name_length 比 length_of_persons_name 好。
  • 慎用小寫字母 l 和大寫字母 O ,因為它們可能被人錯看成數字 1 和 0 。
    # vim hello_world.py
    message = "hello world"   #定義一個變量
    print(message)
    message = "hello python world"
    print(message)
    輸出信息:
    hello world
    hello python world
    python將記錄變量最新值

2.2字符串

    1. pyhon 中,用引號括起的都是字符串,其中的引號可以是單引號,也可以是雙引號。例如:
      print(‘I told my friend, "Python is my favorite language!"‘)
      print("The language ‘Python‘ is named after Monty Python, not the snake.")
      print("One of Python‘s strengths is its diverse and supportive community.")
  • 2.調用一些簡答的方法進行處理 格式: 實例名.方法名
    >>> name = "test_name"
    >>> print(name.title())
    Test_Name
    >>> print(name.upper())
    TEST_NAME
    >>> print(name.lower())
    test_name
    其他方法:
    rstrip()  刪除字符串右側空白
    lstrip()  刪除左側空白
    strip()   刪除兩端空白
  • 3.字符串 合並或拼接 用+號
    制表符:"\t"
    換行符:"\n"
    first_name = "ada"
    last_name = "lovelace"
    full_name = first_name + " " + last_name
    print("Hello, " + full_name.title() + "!")
    print("Languages:\nJavaScript\n\t Python")

    註意:在 Python 2 中,無需將要打印的內容放在括號內。從技術上說, Python 3 中的 print 是一個函數,因此括號必不可少。有些 Python 2 print 語句也包含括號,但其行為與 Python 3 中
    稍有不同。簡單地說,在 Python 2 代碼中,有些 print 語句包含括號,有些不包含

  • 函數的使用方式 #函數名(參數名)
    使用str()
    age = 23
    message = "Happy " + str(age) + "rd Birthday!"
    print(message)

2.3數字

  • 整數 :+ - x / 取余:% 乘方:**

    實例:(2 + 3) * 4

  • 浮點數 Python 將帶小數點的數字都稱為 浮點數
    從很大程度上說,使用浮點數時都無需考慮其行為。你只需輸入要使用的數字, Python 通常都會按你期望的方式處理它們

2.4添加 註釋

註釋用井號( # )標識。井號後面的內容都會被 Python 解釋器忽略,如下所示:
comment.py
```#向大家問好
print("Hello Python people!")

## 2.5python 之禪  .指導原則
編程語言 Perl 曾在互聯網領域長期占據著統治地位,早期的大多數交互式網站使用的都是 Perl 腳本。彼時, “ 解決問題的辦法有多個 ” 被 Perl 社區奉為座右銘。這種理念一度深受大家
的喜愛,因為這種語言固有的靈活性使得大多數問題都有很多不同的解決之道。在開發項目期間,這種靈活性是可以接受的,但大家最終認識到,過於強調靈活性會導致大型項
目難以維護:要通過研究代碼搞清楚當時解決復雜問題的人是怎麽想的,既困難又麻煩,還會耗費大量的時間

import this

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren‘t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you‘re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it‘s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let‘s do more of those!
蒂姆彼得斯的Python的禪宗
美麗勝於醜陋。
顯式比隱式更好。
簡單勝於復雜。
復雜比復雜更好。
Flat比嵌套更好。
稀疏比密集好。
可讀性計數。
特殊情況不足以打破規則。
雖然實用性勝過純凈。
錯誤不應該默默通過。
除非明確沈默。
面對歧義,拒絕猜測的誘惑。
應該有一個 - 而且最好只有一個 - 明顯的做法。
盡管這種方式一開始可能並不明顯,除非你是荷蘭人。
現在比永遠好。
雖然現在永遠不會比*正確*更好。
如果實現很難解釋,這是一個壞主意。
如果實現很容易解釋,這可能是一個好主意。
命名空間是一個好主意 - 讓我們做更多的這些!
## 第三章 列表( 索引  元素的值   組織列表)
###  3.1列表 (索引 元素增刪改查)
一系列按特定序列排列的元素組成。給列表啟一個表示復數的名稱是個不錯的選擇。在 用方括號[ ] 來表示列表,並用逗號來分隔其中的元素。
下面是一個簡單的列表示例,這個列表包含幾種自行車:

bicycles = [‘trek‘, ‘cannondale‘, ‘redline‘, ‘specialized‘]
print(bicycles)

* 訪問列表元素 需要指定元素的位置或索引 
  print(bicycles[0])   
* 索引 從0開始不是1 
     print(bicycles[3])          ##要訪問第四個列表元素,可使用索引 3
     print(bicycles[-1].title()) ##對最後一個元素使用title()方法
* 元素的增刪改

增:
列表末尾添加元素 方法 append() 將元素 添加到了列表末尾,而不影響列表中的其他所有元素:
motorcycles = [] ##定義空列表
motorcycles.append(‘honda‘)
motorcycles.append(‘yamaha‘)
motorcycles.append(‘suzuki‘)
print(motorcycles)
插入:
使用方法insert()可以在列表的任意位置添加元素,但是需要指定索引以及值。
motorcycles.insert(0, ‘ducati‘) #指定索引以及值
motorcycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘]
print(motorcycles)
motorcycles[0] = ‘ducati‘
print(motorcycles)
刪:根據位置或值來刪除列表中的元素。
del 語句 條件是知道其索引,刪除後,你就無法再訪問它
del motorcycles[1]
pop() 方法:彈出列表末尾的元素 列表就像一個棧,而刪除列表末尾的元素相當於彈出棧頂元素。 將元素從列表中刪除,並接著使用它的值將其保存在變量中
popped_motorcycle = motorcycles.pop()
first_owned = motorcycles.pop(0) ##指定索引刪除特定的值
*** remove()方法: 知道要刪除的元素的值,可使用方法 remove()
motorcycles = [‘honda‘, ‘yamaha‘, ‘suzuki‘, ‘ducati‘]
print(motorcycles)
too_expensive = ‘ducati‘
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.") #變量中保存刪除的元素
回顯信息:
[‘honda‘, ‘yamaha‘, ‘suzuki‘, ‘ducati‘]
[‘honda‘, ‘yamaha‘, ‘suzuki‘]
A Ducati is too expensive for me.
註意:方法 remove() 只刪除第一個指定的值。如果要刪除的值可能在列表中出現多次,就需要使用循環來判斷是否刪除了所有這樣的值。
將在第七章使用循環處理上述問題

### 3.2 組織列表的常見方式:sort()、 倒序打印列表  、 sorted()  、確定列表的長度}

使用方法 sort() 對列表元素按字母排序 永久排序
cars = [‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘]
cars.sort() #字母順序
cars.sort(reverse=True) #字母倒序 向 sort() 方法傳遞參數 reverse=True
使用方法 reverse() 反轉列表元素的排列順序 永久排序
cars = [‘bmw‘, ‘audi‘, ‘toyota‘, ‘subaru‘]
print(cars)
cars.reverse()
print(cars)
使用sorted()函數進行臨死性排序 格式: 函數名(傳遞給函數的參數)
sorted(cars)
[‘audi‘, ‘bmw‘, ‘subaru‘, ‘toyota‘]
函數 len() 可快速獲悉列表的長度
len(cars)


## 第四章 操作列表
** 遍歷列表 切片 遍歷切片 復制切片  元組(定義 遍歷 修改元組變量) **

### 4.1  遍歷列表   創建數字列表  列表解析
* 使用for循環遍歷列表中的元素,縮進的大媽行都是循環體的一部分
   magicians = [‘alice‘, ‘david‘, ‘carolina‘]
      for magician in magicians:     ##註意冒號不要丟
                 print(magician.title() + ", that was a great trick!")
                 print("I can‘t wait to see your next trick, " + magician.title() + ".\n")
      print("Thank you, everyone. That was a great magic show!")  ##循環結束後的語句

* 使用range() 函數生成一系列數字 Python 從你指定的第一個值開始數,並在到達你指定的第二個值後停止,因此輸出不包含第二個值(這裏為 5)

      for value in range(1,5):
              print(value)
* 創建數字列表  使用list()函數將range()的結果轉話為列表,將range()作  為list()的參數,輸出一個數字列表。
      numbers = list(range(1,6))    ##range(1,10,2) 可以指定步長(起始,結束,步長)
        print(numbers)
創建列表實例:   
            squares = [] 
            for value in range(1,11):
                    square = value**2
                    squares.append(square)
            print(squares)
            結果:
            [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
* 簡單統計計算     函數(參數)
        min(digits)
        max(digits)
        sum(digits)
* 列表解析
要使用這種語法,首先指定一個描述性的列表名,如 squares ;然後,指定一個左方括號,並定義一個表達式,用於生成你要存儲到列表中的值。在這個示例中,表達式為 value**2 ,它計算平方值。接下來,編寫一個 for 循環,用於給表達式提供值,再加上右方括號。在這個示例中, for 循環為 for value in range(1,11) ,它將值1~10 提供給表達式 value**2 。
註意,這裏的 for 語句末尾沒有冒號。
        squares = [value**2 for value in range(1,11)]
        print(squares)
        結果與你在前面看到的平方數列表相同:
        [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

### 4.2 切片 遍歷切片 復制列表
* 切片:對列表的部分元素進行處理
        players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]
        print(players[0:3]) 
        print(players[1:4]) #提取列表的第 2~4 個元素
        print(players[:4])  #不指定第一個索引默認為開頭
        print(players[2:])  #到列表末尾
        負數索引返回離列表末尾相應距離的元素,因此你可以輸出列表末尾的任何切片。例如,如果你要輸出名單上的最後三名隊員:
        可使用切片 players[-3:] 
* 遍歷切片 在for循環中遍歷切片
        players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]
        print("Here are the first three players on my team:")
        for player in players[:3]:
        print(player.title())
* 復制列表
可創建一個包含整個列表的切片,同時省略起始索引和終止索引( [:] )。

        ----------------------------------------------------------------
        my_foods = [‘pizza‘, ‘falafel‘, ‘carrot cake‘]
        friend_foods = my_foods[:]     #起始末尾復制列表
        ----------------------------------------------------------------
        my_foods = [‘pizza‘, ‘falafel‘, ‘carrot cake‘]
        ? friend_foods = my_foods[:]     #復制列表
        ? my_foods.append(‘cannoli‘)
        ? friend_foods.append(‘ice cream‘)
        print("My favorite foods are:")
        print(my_foods)
        print("\nMy friend‘s favorite foods are:")
        print(friend_foods)
        ----------------------------------------------------------------
        ? friend_foods = my_foods   #僅僅簡單賦值
        my_foods.append(‘cannoli‘)
        friend_foods.append(‘ice cream‘)
        print("My favorite foods are:")
        print(my_foods)
        print("\nMy friend‘s favorite foods are:")
        print(friend_foods)
    註意:這裏將 my_foods 賦給 friend_foods ,而不是將 my_foods 的副本存儲到 friend_foods (見?)。這種語法實際上是讓 Python 將新變量 friend_foods 關聯到包含在 my_foods 中的列表,因此這兩個變量都指向同一個列表。鑒於此,當我們將 ‘cannoli‘ 添加到 my_foods 中時,它也將出現在 friend_foods 中;同樣,雖然 ‘icecream‘ 好像只被加入到了 friend_foods 中,但它也將出現在這兩個列表中。
### 4.3 元組 (定義 遍歷 修改)
* 元組: 列表非常適合用於存儲在程序運行期間可能變化的數據集。列表是可以修改的,這對處理網站的用戶列表或遊戲中的角色列表至關重要。然而,有時候你需要創建一系列不可修改的元素,元組可以滿足這種需求。 Python 將不能修改的值稱為 不可變的 ,而不可變的列表被稱為 元組。
        dimensions = (200, 50)   #(定義元組元素的值,號分割)
        ? dimensions[0] = 250   #不可給元組的元組的元素賦值
        ?處的代碼試圖修改第一個元素的值,導致 Python 返回類型錯誤消息。由於試圖修改元組的操作是被禁止的,因此 Python 指出不能給元組的元素賦值:
        Traceback (most recent call last):
        File "dimensions.py", line 3, in <module>
        dimensions[0] = 250
        TypeError: ‘tuple‘ object does not support item assignment
* for遍歷元組
        dimensions = (200, 50)
        for dimension in dimensions:
        print(dimension)
* 修改元組變量
雖然不能修改元組的元素,但可以給存儲元組的變量賦值。因此,如果要修改前述矩形的尺寸,可重新定義整個元組:
        ? dimensions = (200, 50)
        print("Original dimensions:")
        for dimension in dimensions:
        print(dimension)
        ? dimensions = (400, 100)
        ? print("\nModified dimensions:")
        for dimension in dimensions:
        print(dimension)
## 第五章 條件測試if語句
每條 if 語句的核心都是一個值為 True 或 False 的表達式,這種表達式被稱為 條件測試 。 Python 根據條件測試的值為 True 還是 False 來決定是否執行 if 語句中的代碼。如果條件測試的值為 True , Python 就執行緊跟在 if 語句後面的代碼;如果為 False , Python 就忽略這些代碼。
## 第六章 字典 bash關聯屬組(創建 添加鍵值對 修改   遍歷字典)  嵌套(列表-字典 字典-列表  字典-字典)

## 第七章 用戶輸入和while循環
## 第八章 函數(定義 傳遞參數的不通方式 返回值 傳遞列表  將函數存儲在模塊中) 
## 第九章 類(創建使用 實例化 繼承 導入類 python標準庫)
## 第十章 文件和異常
## 第十一章 測試代碼

python 從入門到實踐 ---基礎篇筆記