變量賦值
Python中的變量不需要聲明,變量的賦值操作既是變量聲明和定義的過程。
每個變量在內存中創建,都包括變量的標識,名稱和數據這些信息。
每個變量在使用前都必須賦值,變量賦值以后該變量才會被創建。
等號(=)用來給變量賦值。
等號(=)運算符左邊是一個變量名,等號(=)運算符右邊是存儲在變量中的值。例如:
#!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 # 賦值整型變量 miles = 1000.0 # 浮點型 name = "John" # 字符串 print counter print miles print name
以上實例中,100,1000.0和"John"分別賦值給counter,miles,name變量。
執行以上程序會輸出如下結果:
100 1000.0 John
多個變量賦值
Python允許你同時為多個變量賦值。例如:
a = b = c = 1
以上實例,創建一個整型對象,值為1,三個變量被分配到相同的內存空間上。
您也可以為多個對象指定多個變量。例如:
a, b, c = 1, 2, "john"
以上實例,兩個整型對象1和2的分配給變量a和b,字符串對象"john"分配給變量c。
Python賦值運算符
以下假設變量a為10,變量b為20:
以下實例演示了Python所有賦值運算符的操作:
#!/usr/bin/python a = 21 b = 10 c = 0 c = a + b print "Line 1 - Value of c is ", c c += a print "Line 2 - Value of c is ", c c *= a print "Line 3 - Value of c is ", c c /= a print "Line 4 - Value of c is ", c c = 2 c %= a print "Line 5 - Value of c is ", c c **= a print "Line 6 - Value of c is ", c c //= a print "Line 7 - Value of c is ", c
以上實例輸出結果:
Line 1 - Value of c is 31 Line 2 - Value of c is 52 Line 3 - Value of c is 1092 Line 4 - Value of c is 52 Line 5 - Value of c is 2 Line 6 - Value of c is 2097152 Line 7 - Value of c is 99864
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com