I'm just learning python. I'm trying to figure out while loops with s.argv in a larger script on my network. hopefully this small example will show basically what i'm trying to do.

argtest.py

import sys

for arg in sys.argv:
print arg
#which gives me:
Life
is
good
but
could
be
better

using a while loop i'm trying to print out the last 4 arguments:
"but could be better", while allowing any additional arguments i add to be printed (8,9,10,so on)

I'm trying to do this with a list of servers in my network but this a shorter example.

I'm sure most of you can do this in your sleep but i'm just learning and it's not so easy for me.

I would greatly appreciate any assistance.
thanks.

So basically do you always want the last 4 arguments printed out? Because if that is the case i wouldn't use a while loop i would go something like this:

import sys

#-4 means start from the back and count back 4
#and then the rest of the arguments (:
for arg in sys.argv[-4:]:
    print arg

Hope that helps ;)

So basically do you always want the last 4 arguments printed out? Because if that is the case i wouldn't use a while loop i would go something like this:

import sys

#-4 means start from the back and count back 4
#and then the rest of the arguments (:
for arg in sys.argv[-4:]:
    print arg

Hope that helps ;)

i would prefer to the example you provided but i think part of the deal is me learning while loops. I've seen several examples of while loops but couldn't make it work with the above criteria.

Thanks,

From what you've said, it sounds like you have to print out elements 3 through 6 (if 0 is the first element) of a list. This will print those 4 elements, doesn't matter how long the list is.

n = 3
while n <= 6:
   print lst[n]
   n += 1

You could also use a for loop:

for x in range(3,7):
   print lst[x]

So, i would replace "n" the 3rd argument?

thanks for the help.

Actaully if you wanted the third item till the sixth item, the above code would almost be correct. Apart from one thing:

#n = 3
#if n = 3, then the fourth item will be printed 
n=2

while n <= 6:
   print lst[n]
   n += 1

This is because a list counts from 0, then 1,2,3 and so on. So when you go list[2] you're actually asking for the 3rd element in the list.

Hope that helps :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.