Rob Carr
Rob Carr

Reputation: 270

Python built-in range function and variable values

I'm writing a script where I extract command line arguments using getopt, qualify the values offered, then use those values as limits on a loop. Code fragment is below:

try:
    start_pod, end_pod, topo_value = map(int, args)
except ValueError, error_msg:
    if 'invalid' in str(error_msg):
        err_funct('Non-integer values supplied: {%s}' % args)
    else:
        err_funct(error_msg)

for pod in range(start_pod, end_pod):
    print 'value of pod: %s' % pod
    for switch in range(1,5):
        print 'value of switch: %s' % switch

The problem I am having is with the 'range' function. I think I am passing it integers (the map function is converting a list of strings to integers) and if I wasn't my try/except handler exits by way of an error function I wrote, but for some reason this isn't working.

If I call my script with the correct number of inputs, e.g. 'some_script.py 1 1 5', the script returns nothing.

Upvotes: 0

Views: 7224

Answers (2)

Thomas Vander Stichele
Thomas Vander Stichele

Reputation: 36529

Please make sure you paste self-contained example. Yours obviously is missing a crucial part - what is args set to ?

If I naively assume that the example you give maps straight to your args and add at the top:

args = ['1', '1', '5']

then it behaves like you just said - no output.

However that is probably not what you want, because then start_pod and end_pod are the same.

If instead I do

args = ['1', '5', '1']

then I get output. What args are reaching your code with the given command line (do print repr(args) in your code right before that block) and what output do you expect from that ?

Upvotes: 1

Mihai Maruseac
Mihai Maruseac

Reputation: 21435

Your call of the script is incorrect:

>>> range(1,1)
[]

(start_pod and end_pod will both be 1).

The range(i,j) functions returns the following list [i, i + 1, .., j - 1]. Or, differently put, the end point is always removed.

Try changing the for pod in range... line in:

for pod in range(start_pod, end_pod + 1):

Upvotes: 2

Related Questions