Pamela
Pamela

Reputation: 475

What's the difference between these two simple codes? More specifically, what is this if statement used for?

I'm reading a book on Python and it's presenting this code:

def myfunc(*args):
    for a in args:
        print(a, end='')
    if args:
        print()

I'm confused what the point of if args is when the code below also shows the same output.

def myfunc(*args):
    for a in args:
        print(a, end='')

Upvotes: 0

Views: 78

Answers (4)

Roberto Caboni
Roberto Caboni

Reputation: 7490

Both versions of your function print the list of arguments it receives.

The end='' parameter makes sure that the \n character is not appended for each print, as would happen by default, printing a line for every argument.

In this way you will have an output like this

arg1arg2...argN<noNewline>

(all the arguments are joined with not even a space separating them). With no end='', instead, you would have had

arg1
arg2
...
argN

Since you might want a trailing newline, in the end you call print(), which just prints a newline. But only if the args list is not empty (if args:), in order to avoid a "strange" empty line even when no arguments are present.

Upvotes: 2

vmemmap
vmemmap

Reputation: 531

*args allows you forward as many arguments to a function as possible. *args always returns set. You are looping over the items in the set, and print each one without new line at the end. In the first code, the condition will return True as long as *args is not None.

def function(*args):
    if *args:
        return f'{args} is not None!`

Upvotes: 1

Lukas Weber
Lukas Weber

Reputation: 1

The first example prints a newline character more if args contains one ore more arguments. I think it's just there to make the output a bit prettier and it is not really important.

Upvotes: 0

JimmyCarlos
JimmyCarlos

Reputation: 1952

if args will be True if any arguments exist.

print() just prints a blank line.

Upvotes: 1

Related Questions