003-python基礎-變數

來源:互聯網
上載者:User

標籤:exce   ima   current   python   odi   第一個字元   代碼   程式   for   

一、變數的定義

變數就是用來在程式運行期間儲存各種需要臨時儲存可以不斷改變的資料的標示符,一個變數應該有一個名字,並且在記憶體中佔據一定的儲存單元,在該儲存單元中存放變數的值。

二、變數的聲明

1 #!/usr/bin/env python2 # -*- coding: utf-8 -*-3   4 name = "wupeiqi"

上述代碼聲明了一個變數,變數名為: name,變數name的值為:"wupeiqi"

變數的作用:暱稱,其代指記憶體裡某個地址中儲存的內容

 

三、變數的命名規則

  • 變數名只能是 字母、數字或底線的任意組合
  • 變數名的第一個字元不能是數字
  • 以下關鍵字不能聲明為變數名
  • [‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘exec‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]

  注意:在python中,大寫字母和小寫字母被認為是兩個不同的字元。因此,sum和SUM是兩個不同的變數名。一般的,變數名用小寫字母表示,與人們的日常習慣一致,以增加可讀性。

 

四、變數名的命名習慣

  變數名的定義在能表達清楚它的作用的前提下越簡潔越好,能用一個單詞表述清楚的就不要用兩個。

  複雜變數命名,選擇底線“_”或首寫字母大寫的形式。如:

  CheckCurrentConnCount

  check_current_conn_count

 

五、變數的賦值及在記憶體中的理解

1 #!/usr/bin/env python2 # -*- coding: utf-8 -*-3 4 name1 = "wupeiqi"5 name2 = "alex"

1 #!/usr/bin/env python2 # -*- coding: utf-8 -*-3 4 name1 = "wupeiqi"5 name2 = name1

當變數name1賦值給另一個變數name2時,解譯器只是把name1所指向的記憶體位址賦值給了name2,因此name1和name2並沒有發生直接的關聯,只不過是他們都同時指向同一個記憶體位址而已,這也就是為什麼你把name1指向一個新地址後,而name2的值還是保持不變的原因。

 1 name1 = "wupeiqi" 2 name2 = "alex" 3 print("name1 id is",id(name1)) 4 print("name2 id is ",id(name2))   5 print("".center(40,"-")) 6 name2 = name1 7 print("name1:", name1) 8 print("name2:", name2) 9 print("name1 id is",id(name1))10 print("name2 id is ",id(name2))11 print("".center(40,"-"))12 name1 = "new"13 print("name1:", name1)14 print("name2:", name2)15 print("name1 id is",id(name1))16 print("name2 id is ",id(name2))17 18 # 輸出19 name1 id is 10728928      # name1的初始id20 name2 id is  10729600     # name2的初始id21 ----------------------------------------22 name1: wupeiqi23 name2: wupeiqi24 name1 id is 1072892825 name2 id is  10728928      # name1把記憶體位址賦值給name226 ----------------------------------------27 name1: new28 name2: wupeiqi29 name1 id is 9362712       # name1指向新的記憶體位址30 name2 id is  10728928     # name2不變

 

003-python基礎-變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.