user10608627
user10608627

Reputation:

Python: "If" function

This is probably really simple but I can't figure it out.

I have a bunch of lists and I want to call certain lists if they are in the range equal to a value x and any number between x-5 and x +5. i.e. x-5,x-4,x-3,x-2,x-1,x,x+1,x+2,x+3,x+4 and x+5.

At the moment I have

if sum(listname[i])==x:

if sum(listname[i])==x-1:

if sum(listname[i])==x-2:

etc

How can I do it so that it is combined in one "if" function.

I've been thinking on the lines of something like:

if sum(listname[i])==x-5>=x>=x+5:

or

if sum(listname[i])==x or x-1 or x-2 ".. etc":

but neither work.

Can anybody shine some light on this?

Upvotes: 1

Views: 187

Answers (4)

chris
chris

Reputation: 21

Do you simply mean

if x-5 <= sum(listname[i]) <= x+5:
    ...
    ...

Upvotes: 2

Talip Tolga Sarı
Talip Tolga Sarı

Reputation: 140

From what I understand from your question. You what to check that whether sum(listname[i]) is between (x-5, x+5)

You can do this in a single if assuming x is a possitive value:

if (sum(listname[i]) >= (x - 5)) and (sum(listname[i]) <= (x+5))

Upvotes: 0

Gniem
Gniem

Reputation: 111

It looks like you want to check if the sum of the list is between x - 5 and x + 5. To put it in one if statement is simply:

s = sum(listname[i])
if s >= x - 5 and s <= x + 5:
  # do stuff

Upvotes: 0

Charles Landau
Charles Landau

Reputation: 4265

A scenario like if sum(listname[i])==x or x-1 or x-2 ".. etc": (which is not valid python) is usually solved with if value in range(start, stop, step):

So you would write:

if sum(listname[i) in range(x-2, x):
    # Code for this case here...

Upvotes: 3

Related Questions