一、Python
Python是荷兰计算机程序员Guido van Rossum主要设计和研发的跨平台的计算机程序语言。自90年代诞生,目前已经广泛应用于深度学习、数值计算、统计等人工智能和软件研发领域。后续将把python相关的知识和实践也做相关的博文记录。
# 查看python版本
#python --version
Python 3.6.8 :: Anaconda, Inc.
(base)
二、基本数据类型
首先Python中的变量不进行声明,变量赋值后该变量被创建,所以创建变量时要赋值。
# error
>>> int tmp_var
File "<stdin>", line 1
int tmp_var
^
SyntaxError: invalid syntax
# error 2
>>> int tmp_var=1
File "<stdin>", line 1
int tmp_var=1
^
SyntaxError: invalid syntax
1、布尔型(Bool)
# bool type: True/False, not true, false
>>> tmp_bool_True=True
>>> tmp_bool_False=False
>>> print(tmp_bool_True)
True
>>> print(tmp_bool_False)
False
>>> tmp_bool_true=true
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
2、数字类型(Number)
1)整数(int)
2)浮点数(float)
3)复数(complex)
3、字符串(String)
1)str
2)string
4、字节类型(Binary Sequence)
1)bytes
2)bytearray
3)memoryview
5、集合(Set)
1)set
2)frozenset
6、元组(Tuple)
7、列表(List)
8、字典(Dictionary)
# dict get value of key
xxx.get('key')
xxx['key']
注意:当我们定义变量时,总是先创建一块内存空间,将值存到这块内存空间上(如int32存在4个字节的空间上),然后把这块内存空间的地址放到变量名里。python的数据类型分为不可变和可变两种类型:
1)可变类型:只改变数据类型的值,而不改变这个数据类型的值存放的内存空间
2)不可变类型:当改变数据类型的值时,会重新申请一块新的内存空间,即变量名里存放的地址也变了
上述类型中Bool、Number、String、Binary、Tuple是不可变类型,Set、List、Dict是可变类型。以上数据格式的定义、说明和相应的操作见python的Built-in types链接https://docs.python.org/3.9/library/stdtypes.html#textseq。
查看变量的数据类型,用内置函数type实现
>>> xxx = 'i love you.'
>>> type(xxx)
<class 'str'>
>>> yyy = 1314.520
>>> type(yyy)
<class 'float'>
三、数据类型转换
1、int函数
1)浮点数转化成整数,直接取整,并不会四舍五入
>>> int(111.11)
111
>>> int(0.10101)
0
>>> int(0.8708)
0
2)字符串转化成整数,字符串需满足整数的格式
>>> int('111')
111
>>> int('111.11')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '111.11'
>>> int('111a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '111a'
2、float函数
1)整数转化成浮点数
>>> float(111)
111.0
>>> float(0)
0.0
>>> float(-1)
-1.0
2)字符串转化成浮点数,字符串需满足浮点数的格式
>>> float('111')
111.0
>>> float('11.1')
11.1
>>> float('-0.111')
-0.111
>>> float(111a)
File "<stdin>", line 1
float(111a)
^
SyntaxError: invalid syntax
>>> float('1a11')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1a11'
3、str函数
1)整数或者浮点数转化成字符串
>>> str(111.11)
'111.11'
>>> str(111)
'111'
>>> str(0)
'0'
>>> str(0.0101)
'0.0101'
>>> str(-0.0101)
'-0.0101'
>>> str(111a)
File "<stdin>", line 1
str(111a)
^
SyntaxError: invalid syntax
2)字符串转化成字符串
>>> str('abcde')
'abcde'
>>> str('111.111')
'111.111'
>>> str('-0.1010')
'-0.1010'
引用
【1】Documentation:https://docs.python.org/3.9/
【2】Tutorial:https://docs.python.org/3.9/tutorial/index.html
【3】The Python Standard Library:https://docs.python.org/3.9/library/index.html#library-index
【4】Built-in Types:https://docs.python.org/3.9/library/stdtypes.html
【5】https://blog.csdn.net/qq_45905052/article/details/104405982