
文章目录
- python学习笔记-3. python基本数据类型
- 前言
- 一、python变量
- 二、数值类型
- 三、字符串类型
- 四、列表类型
- 总结
前言
主要记录python的基本数据类型,python官方文档地址:https://docs.python.org/3/tutorial/index.html
一、python变量
python变量命名规则与其他语言基本一致,但是在定义变量时无需声明变量的类型,可以直接定义赋值,如下:
a = 1
b = 2
test = 'beautiful'
二、数值类型
python中数值类型包含int、float、complex,定义如下:
# 注意int_ float_ complex_ 只是为了方便标示,并非声明的变量类型,不要混淆
int_a = 1
float_b = 1.3
complex_c = 3x
# 可以使用type函数查看类型是否正确
print(type(int_a))
print(type(float_b))
print(type(complex_c))
三、字符串类型
字符串定义,值用单引号或双引号包起来即可,如下:
# 单引号
a = 'testmsg'
print(a)
# 双引号
b = "testmsg"
print(b)
# 上面定义的2个字符串执行打印结果是一致的
转义相关:
# 使用\进行转义,如下语句执行完成后有换行效果
a = 'testmsg\n'
b = 1
print(a)
print(b)
# 使用r忽略转移作用,如下打印:testmsg\n
a = r'testmsg\n'
print(a)
# +连接字符串,打印:testmsgthis
a = 'testmsg'
b = 'this'
print(a+b)
# 使用f引用其他变量,打印:this is msg
a = 'msg'
b = f'this is {a}'
print(b)
# 使用format引用, 打印: this is msg
a = 'msg'
b = 'this is {}'
print(b.format(a))
# 稍微复杂写法如下,打印:this is python msg
a = 'msg'
b = 'python'
c = 'this is {x} {y}'
print(c.format(x=b, y=a))
四、列表类型
列表定义及简单使用如下:
# 列表定义,建议变量名为list_name的格式
list_a = [1, 2, 3, 'test1', 'test2']
# 使用索引取列表里面的值,打印:test1
print(list_a[3])
# 简单使用切片,[]中第一个参数代表切片起始位置,第二个参数代表截止位置,为开闭区间实际取到第2位,打印:[1, 2, 3]
print(list_a[0:3])
总结
记录python的基本数据类型。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)