0

I have a script that is supposed to compare my argument number with two other numbers. If its between them it should return true, if not false

#!/usr/bin/python3

import sys

obj1 = int(sys.argv[1])
obj2 = (1900, 2100)
def range_check(obj1, obj2):
        if obj1 in range(obj2):
                return True
        else:
                return False

print(range_check(obj1, obj2))

I keep on getting "tuple integer error". Please help!

1

2 Answers 2

3

When used the way you're trying to use it, the range() function wants two arguments: start and stop, not a single tuple with the two values. There are many ways to give it two values:

  1. Unpack the tuple into two variables by assignment and pass those variables:
def range_check(obj1, obj2):
    range_start, range_stop = obj2
    return obj1 in range(range_start, range_stop)
  1. Index into the tuple:
def range_check(obj1, obj2):
    return obj1 in range(obj2[0], obj2[1])
  1. Unpack the tuple while passing it to range() using *:
def range_check(obj1, obj2):
    return obj1 in range(*obj2)

Also note:

if a == b: 
    return True
else
    return False

is identical to

return a == b

because a == b is already True or False.

Sign up to request clarification or add additional context in comments.

Comments

1

The issue you have is that the tuple needs to be unpacked. You can do this with the * operator like so:

import sys

obj1 = int(sys.argv[1])
obj2 = (1900, 2100)

def range_check(integer_value, valid_range):
    return integer_value in range(*valid_range)

print(range_check(obj1, obj2))

As noted in another answer, you can omit the broken-out if statement. Also, it is best practice to use arguments that are not variables in the outer scope. This way you don't have any strange behavior with collisions shadowing one another unexpectedly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.