+ 1

How to test if a float number exists between two int numbers?

Lets say the number is 4.5 and we want to see if its between 1-10. x = 4.5 If x in range(1,11): Print(”exists”) Else: Print(”none”) This Would surely not work.

15th Feb 2022, 12:30 PM
Lenoname
8 ответов
+ 8
Lenoname use the comparison operator <. if 1<x and x<10: Python also lets you shorten that to this: if 1<x<10: print("exists") else: print("none")
15th Feb 2022, 1:09 PM
Brian
Brian - avatar
+ 5
Start and stop arguments should be separated using a comma in range() Btw, range() doesn't return floats. Better you try using numpy arange in this context.
15th Feb 2022, 12:38 PM
Simba
Simba - avatar
+ 3
Try this import numpy print(numpy.arange(1,11,0.5)) print(numpy.arange(1,11,0.01)) if statement is executed, if x is included in array otherwise it moves to else part.
15th Feb 2022, 2:02 PM
Simba
Simba - avatar
+ 1
Step argument takes 1 by default means if it's not provided its value is 1. So, numpy.arange(1,11,1) returns 1,2,...10 To include floats, you can do it like this numpy.arange(1,11,0.5)
15th Feb 2022, 1:55 PM
Simba
Simba - avatar
0
Simba If x in numpy.arange(1,11): print(”exists”)?
15th Feb 2022, 12:52 PM
Lenoname
0
Simba And if its 4.01 then it should be numpy.arange(1,11,0.01) i suppose or is it enough with 0.5?
15th Feb 2022, 1:58 PM
Lenoname
0
def number_exist(fnum, num1, num2): return 'exists' if num1<fnum<num2 else 'none'
16th Feb 2022, 9:21 AM
Andrey
0
Try int(x) instead of x
16th Feb 2022, 4:05 PM
Nam Lu
Nam Lu - avatar