Python基础知识(类型转换_str()函数与int()函数、类型转换_float()函数、Python中的注释、)
为什么需要数据类型转换?
将不同数据类型的数据拼接在一起
name='张三'
age=20
print(type(name),type(age))#说明name与age的数据类型不相同
print('我叫'+name+'今年,'+str(age)+'岁')#将int类型通过str()函数转成了str类型
#结果
<class 'str'> <class 'int'>
我叫张三今年,20岁
name='张三'
age=20
print(type(name),type(age))#说明name与age的数据类型不相同
print('我叫'+name+'今年,'+age+'岁')#当将str与int类型进行连接时,报错,解决方案,类型转换
#结果
print('我叫'+name+'今年,'+age+'岁')#当将str与int类型进行连接时,报错,解决方案,类型转换
TypeError: can only concatenate str (not "int") to str
16.类型转换_float()函数
数据类型转换
为什么需要数据类型转换?
讲不同数据类型的数据拼接在一起
s1='13.14'
s2='52'
l1=True
s3='hello'
i=100
print(type(s1),type(s2),type(l1),type(s3),type(i))
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(l1),type(float(l1)))
#print(float(s3),type(float(s3))) #字符串中的数据如果是非数字串,则不允许转换
print(float(i),type(float(i)))
#结果
<class 'str'> <class 'str'> <class 'bool'> <class 'str'> <class 'int'>
13.14 <class 'float'>
52.0 <class 'float'>
1.0 <class 'float'>
100.0 <class 'float'>
函数名str() 作用:将其他数据类型转换成字符串 注意:也可用引号转换
#方法一
l=12.3
print(type(l))
print(str(12.3))
#结果
<class 'float'>
12.3
#方法二
l=12.3
print(type(l))
print('12.3')
#结果
<class 'float'>
12.3
函数名int() 作用:将其他数据类型转换成整数 注意:文字类和小数类字符串,无法转换成整数 浮点数转换成整数:抹零取整
l=9.8
print(type(l))
print(int(l))
#结果
<class 'float'>
9
函数float() 作用:将其他数据类型转换成浮点数 注意:文字类无法转换成整数 整数转换成浮点数,末尾为.0
l=9.9
print(type(l))
print(int(l))
#结果·
<class 'float'>
9
17.Python中的注释
注释
在代码中对代码的功能进行解释说明的标注性文字,可以提高代码的可读性
注释的内容会被Python解释器忽略
通常包括三种类型的注释
1.单行注释--以"#"开头,直到换行结束
2.多行注释--并没有单独的多行注释标记,将一对三引号之间的代码称为多行注释
3.中文编码声明注释--在文件开头加上中文声明注释,用以指定源代码文件的编码格式
#coding:gbk