深入解析Python中的变量和赋值运算符
作者:goldensun 时间:2023-10-13 20:58:53
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
标签:Python,变量,赋值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3处理含有中文的url方法
2021-04-10 02:42:45
![](https://img.aspxhome.com/file/2023/8/92318_0s.jpg)
Linux 安装JDK Tomcat MySQL的教程(使用Mac远程访问)
2024-01-16 12:12:47
![](https://img.aspxhome.com/file/2023/5/110135_0s.jpg)
Python 敏感词过滤的实现示例
2021-07-04 12:17:28
vue 使用vant插件做tabs切换和无限加载功能的实现
2024-04-10 13:49:34
![](https://img.aspxhome.com/file/2023/1/139681_0s.gif)
jupyter notebook保存文件默认路径更改方法汇总(亲测可以)
2023-01-12 09:05:07
![](https://img.aspxhome.com/file/2023/5/131635_0s.jpg)
SQL查询的底层运行原理深入分析
2024-01-21 04:43:49
谈点关于checkbox的事情
2010-09-28 14:49:00
Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】 <font color=red>原创</font>
2021-08-21 17:17:21
SQLServer2005 XML数据操作代码
2024-01-27 11:50:17
浅谈数据库日期类型字段设计应该如何选择
2024-01-21 13:55:21
jQuery实现简单复制json对象和json对象集合操作示例
2024-04-16 09:29:17
![](https://img.aspxhome.com/file/2023/7/136627_0s.png)
关于Python的GPU编程实例近邻表计算的讲解
2022-08-06 22:35:37
简单介绍利用TK在Python下进行GUI编程的教程
2023-01-05 21:24:25
![](https://img.aspxhome.com/file/2023/1/80461_0s.gif)
vue3封装侧导航文字骨架效果组件
2024-04-27 16:10:03
![](https://img.aspxhome.com/file/2023/0/132970_0s.gif)
golang操作mongodb的方法
2023-09-15 03:49:24
python 基于dlib库的人脸检测的实现
2022-08-23 22:59:07
![](https://img.aspxhome.com/file/2023/7/68967_0s.jpg)
Python 多线程,threading模块,创建子线程的两种方式示例
2021-06-29 15:49:32
百度百科的图片轮播代码
2009-05-06 12:58:00
详解如何创建并发布一个 vue 组件
2023-07-02 16:49:08
![](https://img.aspxhome.com/file/2023/0/139790_0s.gif)
浅谈MySQL之浅入深出页原理
2024-01-18 20:38:29
![](https://img.aspxhome.com/file/2023/2/128392_0s.jpg)