Lesson 59 Python中的数据类型及其转换
1. 整型
>>> a = 1
>>> print(a)
查看变量的类型
>>> type(a)
<class ‘int’>
2. 浮点型
>>>b = 1.2
>>> print(b)
1.2
>>> type(b)
<class 'float'>
>>> c = westos
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘westos’ is not defined
3. 字符串型
>>> c = 'westos'
>>> print(c)
westos
>>> c = "what's"
>>> print(c)
what's
>>> c = 'what's'
File "<stdin>", line 1
c = 'what's'
^
SyntaxError: invalid syntax
>>> c = 'what\'s'
>>> print(c)
what's
4. bool型(只有两个值:True False 非0即真)
>>> a = 1
>>> bool(a)
True
>>> bool(0)
False
>>> bool('')
False
>>> bool(' ')
True
>>> bool('redhat')
True
当“”中为空时,bool值为false,当“”中有空格或者其他字符时,bool值为true(非0即真)
5. 数据类型之间的转换
>>> a = 1
>>> type(a)
<class 'int'>
>>> float(a)
1.0
>>> type(a)
<class 'int'>
>>> b = float(a)
>>> b
1.0
>>> b = 2.0
>>> int(b)
2
>>> c = 'redhat'
>>> int(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'redhat'
可以看到,字符串类型不能和数值类型进行数据类型转换,会报错
>>> b = 123
>>> str(b)
'123'
>>> c = '123'
>>> int(c)
123
>>> a
1
>>> b
123
>>> c
'123'
6. 在内存中删除一个变量
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> del b
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined