For loop within an If Statement

Question about a lesson I’m on for my class. In the following function, *args is called to allow for more ingredients on the sandwich. This much I understand. The if len(args) > 0 line makes sense as well. If I’m right, this is essentially saying if args has any value, the if statement runs. the for loop is what’s got me a bit confused. I’m wondering if for extra in args should be indented farther and it’s just a mistake in the book, or if I’m not fully understanding.

To me, logically, the for loop should be indented inside of the if statement, since it should only run if there are additional arguments to call in.

Any thoughts?

def print_sandwich(bread, meat, *args): 
    print('{} on {}'.format(meat, bread), end=' ') 
    if len(args) > 0: 
        print('with', end=' ') 
    for extra in args: 
        print(extra, end=' ') 

It doesn’t matter from a technical point. Args will be a tuple with zero or more elements in it.

If it is empty (zero elements), then the for loop won’t run. So the program could be written either way.

>>> for element in ():
...    print("I'm in the loop!")

I do agree that it might be a bit more explicit if you put the loop inside the if block.

1 Like

So essentially the entire point of the if statement is to print “with”? Is there a way to build it all into one statement? Seems like a lot of code to print out one word. My first thought was to put it into the for loop, but I suppose then it would print out “with mustard with lettuce with tomato” etc.

Correct, the if statement exists only to print the word “with”.

Its not really a lot of code. It’s only two lines.

If you really wanted to combine them into one statement, you could do something like:

if args:
    print(f"with {' '.join(args)}", end ="")