Python 變量類型
變量存儲(chǔ)在內(nèi)存中的值。這就意味著在創(chuàng)建變量時(shí)會(huì)在內(nèi)存中開辟一個(gè)空間。
基于變量的數(shù)據(jù)類型,解釋器會(huì)分配指定內(nèi)存,并決定什么數(shù)據(jù)可以被存儲(chǔ)在內(nèi)存中。
因此,變量可以指定不同的數(shù)據(jù)類型,這些變量可以存儲(chǔ)整數(shù),小數(shù)或字符。
變量賦值
Python中的變量不需要聲明,變量的賦值操作既是變量聲明和定義的過(guò)程。
每個(gè)變量在內(nèi)存中創(chuàng)建,都包括變量的標(biāo)識(shí),名稱和數(shù)據(jù)這些信息。
每個(gè)變量在使用前都必須賦值,變量賦值以后該變量才會(huì)被創(chuàng)建。
等號(hào)(=)用來(lái)給變量賦值。
等號(hào)(=)運(yùn)算符左邊是一個(gè)變量名,等號(hào)(=)運(yùn)算符右邊是存儲(chǔ)在變量中的值。例如:
#!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 # 賦值整型變量 miles = 1000.0 # 浮點(diǎn)型 name = "John" # 字符串 print counter print miles print name
以上實(shí)例中,100,1000.0和"John"分別賦值給counter,miles,name變量。
執(zhí)行以上程序會(huì)輸出如下結(jié)果:
100 1000.0 John
多個(gè)變量賦值
Python允許你同時(shí)為多個(gè)變量賦值。例如:
a = b = c = 1
以上實(shí)例,創(chuàng)建一個(gè)整型對(duì)象,值為1,三個(gè)變量被分配到相同的內(nèi)存空間上。
您也可以為多個(gè)對(duì)象指定多個(gè)變量。例如:
a, b, c = 1, 2, "john"
以上實(shí)例,兩個(gè)整型對(duì)象1和2的分配給變量a和b,字符串對(duì)象"john"分配給變量c。
Python賦值運(yùn)算符
以下假設(shè)變量a為10,變量b為20:
以下實(shí)例演示了Python所有賦值運(yùn)算符的操作:
#!/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
以上實(shí)例輸出結(jié)果:
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
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
