John P. John P. - 1 month ago 8
Python Question

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("https://www.example.com/{num1}/{num2}/{num3}.jpg".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("https://www.example.com/{num1}/{num2}/{num3}.jpg".format(num1=args.num1, num2=args.num2, num3=args.num3))


UPDATE: It is working now. Thanks for all your help.

Answer

shouldn't it be something like this?

import urllib
import argparse

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()

num3 = args.num3

if not num3:
    for num3 in range(01,50):
        download_web_image("https://www.example.com/{num1}/{num2}/{num3}.jpg".format(num1=args.num1, num2=args.num2, num3=num3))
else:
    download_web_image("https://www.example.com/{num1}/{num2}/{num3}.jpg".format(num1=args.num1, num2=args.num2, num3=num3))

your complete code is (sorry) a mess.. first you have to define variables before using them. num3 is not defined in your code, but you check, with if not num3:. And then you use num3 as a variabe in a for-loop - doesn't make any sense to me