深入解析Python中的变量和赋值运算符

yipeiwu_com7年前Python基础

Python 变量类型
变量存储在内存中的值。这就意味着在创建变量时会在内存中开辟一个空间。
基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。
因此,变量可以指定不同的数据类型,这些变量可以存储整数,小数或字符。

变量赋值
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

相关文章

Pytorch 计算误判率,计算准确率,计算召回率的例子

无论是官方文档还是各位大神的论文或搭建的网络很多都是计算准确率,很少有计算误判率, 下面就说说怎么计算准确率以及误判率、召回率等指标 1.计算正确率 获取每批次的预判正确个数 train...

python获取当前文件路径以及父文件路径的方法

python获取当前文件路径以及父文件路径的方法

#当前文件的路径 pwd = os.getcwd() #当前文件的父路径 father_path=os.path.abspath(os.path.dirname(pwd)+os.p...

与Django结合利用模型对上传图片预测的实例详解

1 预处理 (1)对上传的图片进行预处理成100*100大小 def prepicture(picname): img = Image.open('./media/pic/' +...

python中将字典转换成其json字符串

#这是Python中的一个字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': {...

python实现人人网登录示例分享

复制代码 代码如下:import reimport urllib2import cookielib def renren():    cj = cookie...