mercredi 26 octobre 2016

how to make If statement and for loop work for an empty variable

My python script is called dlimage. I want to combine an if statement and a for loop. In the terminal I want to be able to type python dlimage 1 2 3 and it would download only 1 image. Else if the variable of num3 is empty and I type python dlimage 1 2 it would download 50 images by using the for loop for num3 in range(01,50):.

The error when I run python dlimage 1 2:

Traceback (most recent call last):
  File "dlimage.py", line 4, in <module>
    if not num3:
NameError: name 'num3' is undefined

How do I define it, since num3 is already in the parser and url below? Also I am not entirely sure my codes are correct. What's the problem here?

My code:

import urllib
import argparse

if not num3:
    for num3 in range(01,50):

        def download_web_image(url):
            IMAGE = url.rsplit('/',1)[1]
            urllib.urlretrieve(url, IMAGE)

        parser = argparse.ArgumentParser()
        parser.add_argument("num1")
        parser.add_argument("num2")
        parser.add_argument("num3")
        args = parser.parse_args()

        download_web_image("http://ift.tt/2dI72ZP".format(num1=args.num1, num2=args.num2, num3=args.num3))

else:

    def download_web_image(url):
        IMAGE = url.rsplit('/',1)[1]
        urllib.urlretrieve(url, IMAGE)

    parser = argparse.ArgumentParser()
    parser.add_argument("num1")
    parser.add_argument("num2")
    parser.add_argument("num3")
    args = parser.parse_args()

    download_web_image("http://ift.tt/2dI72ZP".format(num1=args.num1, num2=args.num2, num3=args.num3))

Aucun commentaire:

Enregistrer un commentaire