简体   繁体   English

这两个简单的代码有什么区别? 更具体地说,这个 if 语句是做什么用的?

[英]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:我正在阅读一本关于 Python 的书,它提供了以下代码:

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.当下面的代码也显示相同的 output 时,我很困惑if args的意义。

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

Both versions of your function print the list of arguments it receives. function 的两个版本都会打印它收到的 arguments 列表。

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. end=''参数确保不为每个打印附加\n字符,默认情况下会为每个参数打印一行。

In this way you will have an output like this这样,您将拥有像这样的 output

arg1arg2...argN<noNewline>

(all the arguments are joined with not even a space separating them). (所有 arguments 都连接在一起,甚至没有空格分隔它们)。 With no end='' , instead, you would have had相反,如果没有end='' ,您将拥有

arg1
arg2
...
argN

Since you might want a trailing newline, in the end you call print() , which just prints a newline.由于您可能需要一个尾随换行符,所以最后您调用print() ,它只打印一个换行符。 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.仅当 args 列表不为空( if args: )时,才能避免出现“奇怪”的空行,即使没有 arguments 存在。

if args will be True if any arguments exist. if args为 True。

print() just prints a blank line. print()只打印一个空行。

*args allows you forward as many arguments to a function as possible. *args允许您将尽可能多的 arguments 转发到 function。 *args always returns set . *args总是返回set You are looping over the items in the set , and print each one without new line at the end.您正在循环遍历set中的项目,并在最后打印每个项目而不用换行。 In the first code, the condition will return True as long as *args is not None .在第一个代码中,只要*args不是None ,条件就会返回True

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.如果 args 包含一个或多个 arguments,则第一个示例将打印更多换行符。 I think it's just there to make the output a bit prettier and it is not really important.我认为它只是为了让 output 更漂亮一点,这并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM