Python 中的表达式和语句有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4728073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:13:13  来源:igfitidea点击:

What is the difference between an expression and a statement in Python?

pythonexpression

提问by wassimans

In Python, what is the difference between expressions and statements?

在 Python 中,表达式和语句有什么区别?

采纳答案by Sven Marnach

Expressionsonly contain identifiers, literalsand operators, where operators include arithmetic and boolean operators, the function call operator()the subscription operator[]and similar, and can be reduced to some kind of "value", which can be any Python object. Examples:

表达式只包含标识符文字运算符,其中运算符包括算术和布尔运算符、函数调用运算符()订阅运算符[]等,并且可以简化为某种“值”,可以是任何 Python 对象。例子:

3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:

声明(见 12) 另一方面,是可以组成一行(或几行)Python 代码的所有内容。请注意,表达式也是语句。例子:

# all the above expressions
print 42
if x: do_y()
return
a = 7

回答by Flavius

An expression is something that can be reduced to a value, for example "1+3"or "foo = 1+3".

表达式是可以简化为一个值的东西,例如"1+3""foo = 1+3"

It's easy to check:

很容易检查:

print foo = 1+3

If it doesn't work, it's a statement, if it does, it's an expression.

如果它不起作用,它是一个语句,如果它起作用,它是一个表达式。

Another statement could be:

另一种说法可能是:

class Foo(Bar): pass

as it cannot be reduced to a value.

因为它不能减少到一个值。

回答by user225312

Though this isn't related to Python:

虽然这与 Python 无关:

An expressionevaluates to a value. A statementdoes something.

Anexpression评估为一个值。Astatement做某事。

>>> x + 2         # an expression
>>> x = 1         # a statement 
>>> y = x + 1     # a statement
>>> print y       # a statement (in 2.x)
2

回答by Walter Nissen

Python calls expressions "expression statements", so the question is perhaps not fully formed.

Python 将表达式称为“表达式语句”,所以这个问题可能还没有完全形成。

A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#

语句几乎包含您在 Python 中可以执行的任何操作:计算值、赋值、删除变量、打印值、从函数返回、引发异常等。完整列表在这里:http:// docs.python.org/reference/simple_stmts.html#

An expression statement is limited to calling functions (e.g., math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.

表达式语句仅限于调用函数(例如,math.cos(theta)")、运算符(例如,“2+3”)等来生成值。

回答by dawg

Expression-- from the New Oxford American Dictionary:

表达——来自新牛津美式词典

expression: Mathematicsa collection of symbols that jointly express a quantity : the expression for the circumference of a circle is 2πr.

表达式:数学中共同表达一个量的符号集合:圆周长的表达式为 2πr。

In gross general terms: Expressions produce at least one value.

总而言之:表达式至少产生一个值。

In Python, expressions are covered extensively in the Python Language ReferenceIn general, expressions in Python are composed of a syntactically legal combination of Atoms, Primariesand Operators.

在 Python 中,表达式在Python 语言参考中有广泛的介绍。一般来说,Python 中的表达式由AtomsPrimariesOperators的语法合法组合组成。

Python expressions from Wikipedia

来自维基百科的 Python 表达式

Examples of expressions:

表达式示例:

Literalsand syntactically correct combinations with Operatorsand built-in functionsor the call of a user-written functions:

运算符内置函数或用户编写的函数调用的文字和语法正确的组合:

>>> 23
23
>>> 23l
23L
>>> range(4)
[0, 1, 2, 3] 
>>> 2L*bin(2)
'0b100b10'
>>> def func(a):      # Statement, just part of the example...
...    return a*a     # Statement...
... 
>>> func(3)*4
36    
>>> func(5) is func(a=5)
True


Statementfrom Wikipedia:

来自维基百科的声明

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (e.g., expressions).

在计算机编程中,语句可以被认为是命令式编程语言中最小的独立元素。程序由一个或多个语句的序列构成。语句将具有内部组件(例如,表达式)。

Python statements from Wikipedia

来自维基百科的 Python 语句

In gross general terms: Statements Do Somethingand are often composed of expressions (or other statements)

概括地说:语句做某事,通常由表达式(或其他语句)组成

The Python Language Reference covers Simple Statementsand Compound Statementsextensively.

Python 语言参考广泛涵盖了简单语句复合语句

The distinction of "Statements do something" and "expressions produce a value" distinction can become blurry however:

然而,“语句做某事”和“表达式产生值”的区别可能变得模糊:

  • List Comprehensionsare considered "Expressions" but they have looping constructs and therfore also Do Something.
  • The ifis usually a statement, such as if x<0: x=0but you can also have a conditional expressionlike x=0 if x<0 else 1that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;
  • You can write you own Expressions by writing a function. def func(a): return a*ais an expression when used but made up of statements when defined.
  • An expression that returns Noneis a procedure in Python: def proc(): passSyntactically, you can use proc()as an expression, but that is probably a bug...
  • Python is a bit more strict than say C is on the differences between an Expression and Statement. In C, any expression is a legal statement. You can have func(x=2);Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The assignment statement of x=2inside of the function call of func(x=2)in Python sets the named argument ato 2 only in the call to funcand is more limited than the C example.
  • 列表推导式被认为是“表达式”,但它们具有循环结构,因此也可以做一些事情。
  • Theif通常是一个语句,例如if x<0: x=0但您也可以使用条件表达式,例如x=0 if x<0 else 1表达式。在其他语言中,比如 C,这种形式被称为这样的操作符x=x<0?0:1;
  • 您可以通过编写函数来编写自己的表达式。def func(a): return a*a是使用时的表达式,但在定义时由语句组成。
  • 返回的表达式None是 Python 中的一个过程:从def proc(): pass语法上讲,您可以将其proc()用作表达式,但这可能是一个错误...
  • Python 在表达式和语句之间的差异上比 C 更严格一些。在 C 中,任何表达式都是合法的语句。你可以有func(x=2);那是表达式还是语句?(答案:表达式用作具有副作用的语句)Pythonx=2中的函数调用内部的赋值语句仅在调用func(x=2)中将命名参数设置a为 2,func并且比 C 示例更受限制。

回答by abifromkerala

A statement contains a keyword.

语句包含关键字。

An expression does not contain a keyword.

表达式不包含关键字。

print "hello"is statement, because printis a keyword.

print "hello"is 语句,因为printis 是一个关键字。

"hello"is an expression, but list compression is against this.

"hello"是一个表达式,但列表压缩反对这个。

The following is an expression statement, and it is true without list comprehension:

以下是一个表达式语句,在没有列表推导式的情况下为真:

(x*2 for x in range(10))

回答by Emmanuel Osimosu

Statements represent an action or command e.g print statements, assignment statements.

语句表示一个动作或命令,例如打印语句、赋值语句。

print 'hello', x = 1

Expression is a combination of variables, operations and values that yields a result value.

表达式是产生结果值的变量、操作和值的组合。

5 * 5 # yields 25

Lastly, expression statements

最后,表达式语句

print 5*5

回答by Rashid Iqbal

I think an expression contains operators + operands and the object that holds the result of the operation... e.g.

我认为表达式包含运算符 + 操作数和保存操作结果的对象......例如

var sum = a + b;

but a statement is simply a line of a code (it may be an expression) or block of code... e.g.

但语句只是一行代码(它可能是一个表达式)或代码块......例如

fun printHello(name: String?): Unit {
if (name != null)
    println("Hello ${name}")
else
    println("Hi there!")
// `return Unit` or `return` is optional

}

}

回答by ssokhey

Expressions:

表达式:

  • Expressions are formed by combining objectsand operators.
  • An expression has a value, which has a type.
  • Syntax for a simple expression:<object><operator><object>
  • 表达式由objects和组合而成operators
  • 一个表达式有一个值,它有一个类型。
  • 简单表达式的语法:<object><operator><object>

2.0 + 3is an expression which evaluates to 5.0and has a type floatassociated with it.

2.0 + 3是一个表达式,其计算结果为5.0并具有float与之关联的类型。

Statements

声明

Statements are composed of expression(s). It can span multiple lines.

语句由表达式组成。它可以跨越多行。

回答by donald jiang

An expression is something, while a statement does something.
An expression is a statement as well, but it must have a return.

表达式是某物,而语句则是做某事。
表达式也是一个语句,但它必须有一个返回值。

>>> 2 * 2          #expression
>>> print(2 * 2)     #statement

PS:The interpreter always prints out the values of all expressions.

PS:解释器总是打印出所有表达式的值。