问题:为什么在此python代码段中允许使用分号?

Python不保证使用分号来结束语句。那么为什么允许这个(如下)?

import pdb; pdb.set_trace()

Python does not warrant the use of semicolons to end statements. So why is this (below) allowed?

import pdb; pdb.set_trace()

回答 0

Python并不需要分号来终止语句。如果您希望将多个语句放在同一行上,可以使用半冒号来分隔语句。

现在,为什么允许这样做?这是一个简单的设计决定。我认为Python不需要这种分号的东西,但是有人认为将其添加到语言中会很好。

Python does not require semi-colons to terminate statements. Semi colons can be used to delimit statements if you wish to put multiple statements on the same line.

Now, why is this allowed? It’s a simple design decision. I don’t think Python needs this semi-colon thing, but somebody thought it would be nice to have and added it to the language.


回答 1

http://docs.python.org/reference/compound_stmts.html

复合语句由一个或多个“子句”组成。子句由标题和“套件”组成。特定复合语句的子句标题都位于相同的缩进级别。每个子句头均以唯一标识的关键字开头,并以冒号结尾。套件是由子句控制的一组语句。套件可以是在标头的冒号之后,与标头在同一行上的一个或多个用分号分隔的简单语句,也可以是在后续行上的一个或多个缩进语句。只有后者的套件形式可以包含嵌套的复合语句;以下是非法的,主要是因为不清楚else子句属于哪个if子句:

if test1: if test2: print x

还要注意,在这种情况下,分号比冒号绑定更紧密,因此在以下示例中,将执行全部或不执行任何打印语句:

if x < y < z: print x; print y; print z 

总结:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | decorated
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

http://docs.python.org/reference/compound_stmts.html

Compound statements consist of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

if test1: if test2: print x

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print statements are executed:

if x < y < z: print x; print y; print z 

Summarizing:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | decorated
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

回答 2

Python将;用作分隔符,而不是终止符。您还可以在行的末尾使用它们,这使它们看起来像语句终止符,但这是合法的,因为空白语句在Python中是合法的-末尾包含分号的行是两个语句,第二个一个空白。

Python uses the ; as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python — a line that contains a semicolon at the end is two statements, the second one blank.


回答 3

口译中的分号

阅读答案后,我仍然想念使用分号的一个重要方面,可能是唯一真正起作用的方面。

当您在解释器REPL(Python交互式外壳,IDLE,ipython)中工作时,最后一个表达式的值会显示在屏幕上,通常这是预期的行为。

使用表达式产生副作用

但是在某些情况下,您只想评估一个表达式的副作用,例如,查看仿真结果,由 matplotlib

在这种情况下,你(可能)不希望看到的屏面reprmatplotlib对象有时会通过调用返回到matplotlib至少一种功能,在IPython中,你有一种可能性是分号追加到过度冗长的语句,现在IPython看到输入行是由两个表达式(matplotlib调用和null语句)组成的,因此复合表达式的值为,None解释器不会在屏幕上显示任何内容(另一种可能是assign,如_ = plot(...)但我发现这更具侵入性)。

个人评论

恕我直言,在IPyton笔记本电脑问世之后,使用分号在解释器中抑制不想要的输出变得更加相关,该笔记本可以保存解释器会话的输入和输出(包括图形输出),以供文档记录和最终重用。

Semicolon in the interpreter

Having read the answers, I still miss one important aspect of using semicolons, possibly the only one where it really makes a difference…

When you’re working in an interpreter REPL (the Python interactive shell, IDLE, ipython) the value of the last expression is printed to the screen and usually this is the intended behavior.

Using an expression for side effects

But in some cases you want to evaluate an expression for its side effects only, e.g., to see the results of your simulation plotted by matplotlib.

In this cases you (probably) don’t want to see the screenful of reprs of matplotlib objects that are sometimes returned by a call to a matplotlib function and, in IPython at least, one of the possibilities you have is to append a semicolon to the overly verbose statement, now IPython sees the input line as composed by two expressions, the matplotlib invocation and a null statement, so that the value of the compound expression is None and nothing is printed to the screen by the interpreter (the other possibility being assignment, as in _ = plot(...) but I find that a bit more intrusive).

Personal remark

IMHO, the use of the semicolon to suppress not desired output in the interpreter has become more relevant following the introduction of the IPyton notebook, that permits to save the input and the output, including graphical output, of an interpreter session for documentation and eventual reuse.


回答 4

正如其他所有人都指出的那样,您可以使用分号来分隔语句。你不必到,这不是一贯的作风。

至于为什么有用,有些人喜欢在一行上放置两个或多个真正的琐碎的简短声明(我个人认为这会将几条琐碎的,容易浏览的行变成一条看起来很复杂的行,使人很难看清它是琐碎的) 。

但是,当您使用调用Shell中的一个衬板时,这几乎是必需的python -c '<some python code>'。在这里,您不能使用缩进来分隔语句,因此,如果单行代码实际上是两行代码,则需要使用分号。而且,如果您想在单行代码中使用其他参数,则必须导入sys才能到达at sys.argv,这需要单独的import语句。例如

python -c "import sys; print ' '.join(sorted(sys.argv[1:]))" 5 2 3 1 4
1 2 3 4 5

As everyone else has noted, you can use semicolons to separate statements. You don’t have to, and it’s not the usual style.

As for why this is useful, some people like to put two or more really trivial short statements on a single line (personally I think this turns several trivial easily skimmed lines into one complex-looking line and makes it harder to see that it’s trivial).

But it’s almost a requirement when you’re invoking Python one liners from the shell using python -c '<some python code>'. Here you can’t use indentation to separate statements, so if your one-liner is really a two-liner, you’ll need to use a semicolon. And if you want to use other arguments in your one-liner, you’ll have to import sys to get at sys.argv, which requires a separate import statement. e.g.

python -c "import sys; print ' '.join(sorted(sys.argv[1:]))" 5 2 3 1 4
1 2 3 4 5

回答 5

我意识到我作为一个老C程序员有偏见,但是有时候各种Python约定使事情变得难以理解。我发现缩进约定有时会有些烦人。

有时,清楚声明或块结束的时间非常有用。标准C代码通常会读取如下内容:

for(i=0; i<100; i++) {
    do something here;
    do another thing here;
}

continue doing things;

在哪里使用空格可以使内容更加清晰-而且很容易看到循环的结束位置。

Python确实允许您以(可选)分号终止。如上所述,这并不意味着存在要执行的语句,后跟“空”语句。例如

print(x);
print(y);

是相同的

print(x)
print(y)

如果您认为第一个语句在每一行的末尾都有一个null语句,请尝试-按照建议的方式执行以下操作:

print(x);;

它将引发语法错误。

就个人而言,当您具有大量嵌套和带有许多参数和/或长名称的args的函数时,我发现分号可使代码更易读。因此,在我看来,这比其他选择要清楚得多:

if some_boolean_is_true:
    call_function(
        long_named_arg_1,
        long_named_arg_2,
        long_named_arg_3,
        long_named_arg_4
    );

因为对我来说,它使您知道最后的’)’结束了跨越许多行的某些’block’。

我个人认为,PEP样式指南,执行它们的IDE太多了,并且相信“只有一种Python方式可以做事”。如果您相信后者,请看看如何设置数字格式:到目前为止,Python支持四个不同的。

我敢肯定我会被一些顽固分子激怒,但是编译器/解释器不在乎参数是长名称还是短名称,而且-对于Python中的缩进约定-不在乎空格。代码的最大问题是让另一个人(甚至是几个月的工作后的自己)更加清楚地了解正在发生的事情,事情的开始和结束等。

I realize I am biased as an old C programmer, but there are times when the various Python conventions make things hard to follow. I find the indent convention a bit of an annoyance at times.

Sometimes, clarity of when a statement or block ends is very useful. Standard C code will often read something like this:

for(i=0; i<100; i++) {
    do something here;
    do another thing here;
}

continue doing things;

where you use the whitespace for a lot of clarity – and it is easy to see where the loop ends.

Python does let you terminate with an (optional) semicolon. As noted above, that does NOT mean that there is a statement to execute followed by a ‘null’ statement. SO, for example,

print(x);
print(y);

Is the same as

print(x)
print(y)

If you believe that the first one has a null statement at the end of each line, try – as suggested – doing this:

print(x);;

It will throw a syntax error.

Personally, I find the semicolon to make code more readable when you have lots of nesting and functions with many arguments and/or long-named args. So, to my eye, this is a lot clearer than other choices:

if some_boolean_is_true:
    call_function(
        long_named_arg_1,
        long_named_arg_2,
        long_named_arg_3,
        long_named_arg_4
    );

since, to me, it lets you know that last ‘)’ ends some ‘block’ that ran over many lines.

I personally think there is much to much made of PEP style guidelines, IDEs that enforce them, and the belief there is ‘only one Pythonic way to do things’. If you believe the latter, go look at how to format numbers: as of now, Python supports four different ways to do it.

I am sure I will be flamed by some diehards, but the compiler/interpreter doesn’t care if the arguments have long or short names, and – but for the indentation convention in Python – doesn’t care about whitespace. The biggest problem with code is giving clarity to another human (and even yourself after months of work) to understand what is going on, where things start and end, etc.


回答 6

分号是有效语法的一部分:8.复合语句(《 Python语言参考》)

Semicolons are part of valid syntax: 8. Compound statements (The Python Language Reference)


回答 7

引用“ Python攻击时

不要用分号终止所有语句。在Python中执行此操作在技术上是合法的,但是除非您在一行上放置多个语句(例如,x = 1; y = 2; z = 3),否则这是完全没有用的。

A quote from “When Pythons Attack

Don’t terminate all of your statements with a semicolon. It’s technically legal to do this in Python, but is totally useless unless you’re placing more than one statement on a single line (e.g., x=1; y=2; z=3).


回答 8

一行上的多个语句可能包含分号作为分隔符。例如:http : //docs.python.org/reference/compound_stmts.html在您的情况下,它使插入点很容易,从而打入调试器。

而且,正如Mark Lutz在《Python学习书籍》中提到的那样,用分号终止所有语句在技术上是合法的(尽管是不必要和烦人的)。

Multiple statements on one line may include semicolons as separators. For example: http://docs.python.org/reference/compound_stmts.html In your case, it makes for an easy insertion of a point to break into the debugger.

Also, as mentioned by Mark Lutz in the Learning Python Book, it is technically legal (although unnecessary and annoying) to terminate all your statements with semicolons.


回答 9

如果您在一行中包含多个语句,Python确实允许您使用分号来表示语句的结尾。

Python does let you use a semi-colon to denote the end of a statement if you are including more than one statement on a line.


回答 10

分号可用于一行两个或多个命令。它们不必使用,但不受限制。

给定两个分号(;)都不能在一个新的代码块中开始,因此它允许在一行上显示多个语句。

http://www.tutorialspoint.com/python/python_basic_syntax.htm

Semicolons can be used to one line two or more commands. They don’t have to be used, but they aren’t restricted.

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block.

http://www.tutorialspoint.com/python/python_basic_syntax.htm


回答 11

分号(如点,逗号和括号)往往会引起宗教战争。尽管如此,由于各种原因,它们(或一些类似的符号)在任何编程语言中还是有用的。

  • 实用:将几条概念上属于同一条的简短命令放在同一行上的能力。看起来像一条狭窄的蛇的程序文本与换行符和缩进所预期的相反,后者突出显示了结构。

  • 概念上的:在过去称为“漂亮打印”的情况下,纯语法(在这种情况下为命令序列)与表示(例如换行符)之间的关注点分离。

观察:对于突出显示的结构,可以用明显的方式用垂直线增加/替换压痕,用作“视觉标尺”以查看压痕的起点和终点。不同的颜色(例如,遵循电阻器的颜色代码)可以补偿拥挤。

Semicolons (like dots, commas and parentheses) tend to cause religious wars. Still, they (or some similar symbol) are useful in any programming language for various reasons.

  • Practical: the ability to put several short commands that belong conceptually together on the same line. A program text that looks like a narrow snake has the opposite effect of what is intended by newlines and indentation, which is highlighting structure.

  • Conceptual: separation of concerns between pure syntax (in this case, for a sequence of commands) from presentation (e.g. newline), in the old days called “pretty-printing”.

Observation: for highlighting structure, indentation could be augmented/replaced by vertical lines in the obvious way, serving as a “visual ruler” to see where an indentation begins and ends. Different colors (e.g. following the color code for resistors) may compensate for crowding.


回答 12

之所以允许,是因为作者决定允许它:https : //docs.python.org/2/reference/simple_stmts.html

如果质疑作者为什么要这样做,我想是这样,因为至少在以下语言中,允许将半列作为简单的语句终止:C ++,C,C#,R,Matlab,Perl等。

因此,对于有其他语言背景的人们来说,使用Python更快。在这种选择上,也不会失去一般性。

It’s allowed because authors decided to allow it: https://docs.python.org/2/reference/simple_stmts.html

If move to question why authors decided todo so, I guess it’s so because semi-column is allowed as simple statement termination at least in the following langages: C++, C, C#, R, Matlab,Perl,…

So it’s faster to move into usage of Python for people with background in other language. And there are no lose of generality in such deicison.


回答 13

仅在同一块中的语句分离时才需要分号(“;”),例如,如果我们具有以下C代码:

if(a>b)
{
largest=a;  //here largest and count are integer variables
count+=1;
}

可以使用以下两种形式之一用Python编写:

if a>b:   
    largest=a
    count=count+1

要么

if a>b:    largest=a;count=count+1

在上面的示例中,一个if块中可以有任意数量的语句,并且可以用“;”分隔。代替。

希望没有像上面的解释那样简单。

Semicolon (“;”) is only needed for separation of statements within a same block, such as if we have the following C code:

if(a>b)
{
largest=a;  //here largest and count are integer variables
count+=1;
}

It can be written in Python in either of the two forms:

if a>b:   
    largest=a
    count=count+1

Or

if a>b:    largest=a;count=count+1

In the above example you could have any number of statements within an if block and can be separated by “;” instead.

Hope that nothing is as simple as above explanation.


回答 14

补充这里提供的大量知识,
这是与matplotlib库相关的答案

import numpy as np
import matplotlib as plt
%matplotlib notebook
linear_data = np.array([1, 2, 3, 4, 5, 6, 7, 8])
quadratic_data = linear_data**2
plt.figure()
xvals = range(len(linear_data))
plt.barh(xvals, linear_data, height = 0.3, color='b')
plt.barh(xvals, quadratic_data, height = 0.3, left=linear_data, color='r')

如果您在barh(水平条)的末尾不提供分号,则输出为图+函数地址。但是,如果在两条barh行的末尾都使用分号,则它仅显示图并抑制函数地址的输出。

像这样: 比较

Adding to the vast knowledge present here,
This is an answer related to the matplotlib library

import numpy as np
import matplotlib as plt
%matplotlib notebook
linear_data = np.array([1, 2, 3, 4, 5, 6, 7, 8])
quadratic_data = linear_data**2
plt.figure()
xvals = range(len(linear_data))
plt.barh(xvals, linear_data, height = 0.3, color='b')
plt.barh(xvals, quadratic_data, height = 0.3, left=linear_data, color='r')

If you don’t provide a semicolon at the end of the barh(horizontal bar), the output is a plot + a function address. But if you use semicolons at the end of both barh lines,then it only shows the plot and suppresses the output for the function address.

Something like this: Comparison


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。