Python: range function for decimal numbers

前端 未结 4 739
有刺的猬
有刺的猬 2021-01-16 15:22

Is there any range() function in python for float numbers for example

a=0.6

if a in range(0,1):
    a=3

How can i implement this?

4条回答
  •  醉话见心
    2021-01-16 16:08

    If I'm reading correctly, you want to test if a number is between two other numbers, so use:

    a = 0.6
    if 0 <= a < 1: # change to `<= 1` to be inclusive
       a = 3
    

    You don't need to generate a range and do membership testing - unless you have a discrete set of values that your a should match - the builtin range in Python 3.x can do efficient lookups for ints as it can optimise membership testing. If you have a large amount of discrete values in a large range, then you'd be better of doing it mathematically anyway.

提交回复
热议问题