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='')
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.
if args
will be True if any arguments exist.
print()
just prints a blank line.
*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!`
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.