10. python float( )函数
10. python float( )函数
文章目录
- 10. python float( )函数
- 1. float( )函数
- 2. 将int转换为float
- 3. 将str转换成float
- 3.1 整数类型的str
- 3.2 小数类型的str
- 3.3 float( )函数参数为数据本身
- 4. 总结
- 5. 课后练习
- 5.1. 补全代码,原样输出:`奶茶15元`
- 5.2. 补全代码,原样输出:`15杯奶茶225元`
- 5.3. 买10杯以上,店家打7.5折,补全代码,计算输出:`15杯奶茶?元`
- 5.4. 为了方便找补,店家只收到元,不收小数点后的数,计算输出`15杯奶茶168元`
1. float( )函数
【作用】
float( )函数能将str类型、int类型的数据转换成浮点数类型。
【语法】
在Python中函数的语法基本都是函数名
、英文小括号
、参数
三个部分组成。
int( )函数由3部分组成:
1.函数名:float
2.英文小括号:( )
3.要转换的内容。(内容是变量或具体的数据内容)
2. 将int转换为float
# 定义一个变量price,数据类型为整数
price = 7
print("使用type函数查看变量price的数据类型:")
print(type(price))
【终端输出】
使用type函数查看变量price的数据类型:
<class 'int'>
price [praɪs]:单价。
运行上述代码,我们知道变量price的数据类型为int。
# 定义一个变量price,数据类型为整数
price = 7
# 使用float函数将整数转换为浮点数
print(float(price))
print("使用type函数查看float(price)的数据类型:")
print(type(float(price)))
【终端输出】
7.0
使用type函数查看float(price)的数据类型:
<class 'float'>
对于整数,float( )函数会给它加一个.0
,使其变成浮点数。
3. 将str转换成float
3.1 整数类型的str
# 定义一个变量price,数据类型为字符串
price = "15"
print("使用type函数查看变量price的数据类型:")
print(type(price),'\n')
print("输出float(price):")
print((float(price)),'\n')
print("使用type函数查看float(price)的数据类型:")
print(type(float(price)))
【终端输出】
使用type函数查看变量price的数据类型:
<class 'str'>
输出float(price):
15.0
使用type函数查看float(price)的数据类型:
<class 'float'>
代码float(price)
实现了在整数15
后面添加.0
的功能。
【备注】'\n'
是一个转义字符,作用是换行,这里实现了输出完以后有一个空行的效果。
3.2 小数类型的str
# 定义一个变量price,数据类型为字符串
price = "0.8"
print("使用type函数查看变量price的数据类型:")
print(type(price),'\n')
print("输出float(price):")
print((float(price)),'\n')
print("使用type函数查看float(price)的数据类型:")
print(type(float(price)))
【终端输出】
使用type函数查看变量price的数据类型:
<class 'str'>
输出float(price):
0.8
使用type函数查看float(price)的数据类型:
<class 'float'>
代码float(price)
实现了将字符串"0.8"
的引号脱去的功能。
【温馨提示】
小数类型的字符串不能直接转换成整数。
小数类型的字符串可以转换成浮点数。
3.3 float( )函数参数为数据本身
print(float(7))
print(float("100"))
print(float("3.14"))
【终端输出】
7.0
100.0
3.14
4. 总结
【截止目前学过的函数】
1.print( )函数:将print( )函数括号中的内容打印或输出到屏幕上。
2.type( )函数:查询数据类型。
3.str( )函数:将整数、浮点数转换成字符串。
4.int( )函数:将整数型的字符串、浮点数转换成整数。
5.float( )函数:将字符串、整数转换成浮点数。
【难点】
小数类型的字符串不能直接转换成整数。
小数类型的字符串只能先转换成浮点数,再转换成整数。
除了上述小数字符串不能直接转整数外,str、int、float三者是可以互相转换的。
大家只要记住红色部分字体就能完全掌握数据转换了。
红色字体内容是初学者易犯的错误,是难点和重点。
5. 课后练习
5.1. 补全代码,原样输出:奶茶15元
milk_tea = "奶茶"
price = 15
unit_1= "元"
# 原样输出:奶茶15元
unit[ˈjuːnɪt]:单位、单元。
5.2. 补全代码,原样输出:15杯奶茶225元
【注意】数值225需程序自己计算输出,不能人工计算填入。
milk_tea = "奶茶"
price = 15
unit_1 = "元"
unit_2 = "杯"
# 原样输出:15杯奶茶225元
5.3. 买10杯以上,店家打7.5折,补全代码,计算输出:15杯奶茶?元
milk_tea = "奶茶"
price = 15
unit_1 = "元"
unit_2 = "杯"
# 店家打7.5折,计算输出:15杯奶茶?元
【注意】?需程序自己计算输出,不能人工计算填入。
5.4. 为了方便找补,店家只收到元,不收小数点后的数,计算输出15杯奶茶168元
【提示】15杯奶茶打7折后的价格是168.75元,店家抹零只收168元,编写代码让程序自动输出:15杯奶茶168元
milk_tea = "奶茶"
price = 15
unit_1 = "元"
unit_2 = "杯"
# 店家打7.5折,计算输出:15杯奶茶168元