-3

Description: I have three variable a, x and y. I want to apply the following, if variable a in range(x, y) print the a variable

Code:

a = "0.50"
x = "-14.40"
y = "0.50"

for a in range(int(x), int(y)):
    print a

Error (of course):

ValueError: invalid literal for int() with base 10: '-14.40'

Pythonista i need your help here please!!

ME_sociaty
  • 97
  • 1
  • 10

3 Answers3

1

The Python 2 range function is irrelevant for this task. You just need to convert those strings to floats and do simple comparison tests. Eg,

a = "0.50"
x = "-14.40"
y = "0.50"

afloat = float(a)
if float(x) <= afloat and afloat <= float(y):
    print a  

output

0.50

This can be written more simply (and more efficiently) using Python's comparison chaining.

a = "0.50"
x = "-14.40"
y = "0.50"

if float(x) <= float(a) <= float(y):
    print a

FWIW, in Python 3, the range object can be useful for testing membership of a range, but it wouldn't be useful for your case. Eg,

>>> r = range(1, 10, 2)
>>> list(r)
[1, 3, 5, 7, 9]
>>> 3 in r
True
>>> 4 in r
False
>>> 3.5 in r
False
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1

From the comments

i need to check if a in range of x and y or not.

Then do

a = "0.50"
x = "-14.40"
y = "0.50"

if float(x) <= float(a) <= float(y):  # checks a is between x and y (inclusive)
     # do something

range does something very different. It is for making iterators which we can use in for loops, like this:

for i in range(4):
    print(i * 2)
0
2
4
6
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
0

You can use numpy arange.

import numpy as np
r = np.arange(-14.4,0.5, 0.5)

def isinside(x):
if x in r:
    print ("x")
else:
    print ("x no in a")

isinside(-12)

returns

x no in a    

If you want to print the whole serie

print ([round(x) for x in r])# round to avoid long numbers

Some more information https://pynative.com/python-range-for-float-numbers/

Hermes Morales
  • 593
  • 6
  • 17