代码打印9,即使6.33落在第三个IF语句中的范围内,不是零,而是在范围(5,8)内

我还以为它会印第三版呢 代码

address="xyz"
size="6.33"
if address == 0 and float(size) in range(1, 5):
    print("1")
elif address == 0 and float(size) in range(5, 8):          
    print("2")
elif address != 0 and float(size) in range(5, 8):         
    print("3")
elif address == 0 and float(size) in range(8, 10):        
    print("4")
elif address != 0 and float(size) in range(10, 19):         
    print("5")
elif address == 0 and float(size) in range(10, 19):          
    print("6")
elif address != 0 and float(size) in range(20, 100):         
    print("7")
elif address != 0 and float(size) in range(20, 100):   
    print("8")
else:           
    print("9")

如何修复代码,使其能够检测给定范围内的浮点值

推荐答案

range仅生成整数.例如,range(2,6)将生成(2,3,4,5).

您的问题可以通过以下方式解决:

address="xyz"
size="6.33"
if address == 0 and float(size)>=1 and  float(size)<5:
    print("1")
elif address == 0 and float(size)>=5 and  float(size)<8:          
    print("2")
elif address != 0 and float(size)>=5 and  float(size)<8:         
    print("3")
elif address == 0 and float(size)>=8 and  float(size)<10:        
    print("4")
elif address != 0 and float(size)>=10 and  float(size)<19:         
    print("5")
elif address == 0 and float(size)>=10 and  float(size)<19:          
    print("6")
elif address != 0 and float(size)>=20 and  float(size)<100:         
    print("7")
elif address == 0 and float(size)>=20 and  float(size)<100:   
    print("8")
else:           
    print("9")

或者更有效地,使用嵌套条件,

address="xyz"
size="6.33"
if address == 0:
    if float(size)>=1 and  float(size)<5:
        print("1")
    elif float(size)>=5 and float(size)<8:          
        print("2")
    elif float(size)>=8 and float(size)<10:          
        print("4")
    elif float(size)>=10 and float(size)<19:          
        print("6")
    elif float(size)>=20 and float(size)<100:          
        print("8")
    else:
        print("9")
else:
    if float(size)>=5 and float(size)<8:          
        print("3")
    elif float(size)>=10 and float(size)<19:          
        print("5")
    elif float(size)>=20 and float(size)<100:          
        print("7")
    else:
        print("9")

Python相关问答推荐

"Discord机器人中缺少所需的位置参数ctx

如何修复使用turtle和tkinter制作的绘画应用程序的撤销功能

Python中MongoDB的BSON时间戳

在函数内部使用eval(),将函数的输入作为字符串的一部分

使用mySQL的SQlalchemy过滤重叠时间段

如何从在虚拟Python环境中运行的脚本中运行需要宿主Python环境的Shell脚本?

使用setuptools pyproject.toml和自定义目录树构建PyPi包

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

Pandas DataFrame中行之间的差异

在ubuntu上安装dlib时出错

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

如何在TensorFlow中分类多个类

干燥化与列姆化的比较

Flask运行时无法在Python中打印到控制台

从一个df列提取单词,分配给另一个列

每次查询的流通股数量

修改.pdb文件中的值并另存为新的

PYTHON中的pd.wide_to_long比较慢