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

时间:2022-09-06 13:17:25

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

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

11 个解决方案

#1


171  

Expressions only contain identifiers, literals and 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:

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

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

#2


87  

Expression -- from my dictionary:

表达——从我的字典里:

expression: Mathematics a 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 Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.

在Python中,在Python语言引用中,表达式被广泛地覆盖,Python中的表达式由原子、主元素和操作符的语法合法组合构成。

Python expressions from Wikipedia

Python表达式从*

Examples of expressions:

表达式的例子:

Literals and syntactically correct combinations with Operators and built-in functions or 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

Statement from 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 Something and are often composed of expressions (or other statements)

总而言之:语句做了一些事情,通常由表达式(或其他语句)组成

The Python Language Reference covers Simple Statements and Compound Statements extensively.

Python语言引用广泛地包含简单的语句和复合语句。

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

然而,“陈述做某事”和“表达产生价值”的区别可以变得模糊起来:

  • List Comprehensions are considered "Expressions" but they have looping constructs and therfore also Do Something.
  • 列表的理解被认为是“表达式”,但是它们有循环结构,因此也会做一些事情。
  • The if is usually a statement, such as if x<0: x=0 but you can also have a conditional expression like x=0 if x<0 else 1 that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;
  • if通常是一个语句,比如x<0: x=0,但也可以有条件表达式,如x=0,如果x<0,则是表达式。在其他语言中,比如C,这种形式叫做算子x=x<0:1;
  • You can write you own Expressions by writing a function. def func(a): return a*a is an expression when used but made up of statements when defined.
  • 您可以通过编写函数来编写自己的表达式。def func(a): return a*a是使用时的表达式,但在定义时是由语句组成的。
  • An expression that returns None is a procedure in Python: def proc(): pass Syntactically, you can use proc() as an expression, but that is probably a bug...
  • 返回None的表达式是Python中的一个过程:def proc():通过语法,您可以使用proc()作为表达式,但这可能是一个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 form func(x=2) is illegal in Python (or at least it has a different meaning func(a=3) sets the named argument a to 3)
  • Python比C更严格一点,即表达式和语句之间的区别。在C中,任何表达式都是一种法律声明。你可以有func(x = 2);这是一个表达式还是一个语句?(回答:用作陈述的表达,带有副作用。)表单func(x=2)在Python中是非法的(或者至少它有一个不同的含义func(a=3)将命名的参数a设置为3)

#3


43  

Though this isn't related to Python:

虽然这与Python无关:

An expression evaluates to a value. A statement does something.

表达式求值。做一份声明。

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

#4


7  

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

语句表示一个动作或命令e。g打印语句,赋值语句。

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

#5


2  

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.

因为它不能被还原为一个值。

#6


1  

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:解释器总是打印出所有表达式的值。

#7


0  

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中可以做的任何事情:计算值、赋值、删除变量、打印值、从函数返回值、引发异常等等。

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())、运算符(例如,“2+3”)等,以产生一个值。

#8


0  

A statement contains a keyword.

语句包含一个关键字。

An expression does not contain a keyword.

表达式不包含关键字。

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

打印“hello”是语句,因为print是一个关键字。

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

“hello”是一个表达式,但是list压缩是针对这个的。

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

下面是一个表达式语句,没有列表理解是正确的:

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

#9


0  

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

}

}

#10


0  

Expressions:

表达式:

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

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

2.0 + 3是一个计算值为5.0的表达式,并且有一个与之相关联的类型浮动。

Statements

语句

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

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

#11


0  

  1. An expression is a statement that returns a value. So if it can appear on the right side of an assignment, or as a parameter to a method call, it is an expression.
  2. 表达式是返回值的语句。因此,如果它可以出现在赋值的右边,或者作为一个方法调用的参数,它就是一个表达式。
  3. Some code can be both an expression or a statement, depending on the context. The language may have a means to differentiate between the two when they are ambiguous.
  4. 根据上下文,一些代码可以是表达式或语句。这种语言可能有一种方法来区分两者之间的歧义。

Basic Examples

Here are some basic Javascript examples:

下面是一些基本的Javascript示例:

These are statements. (You can't use them as a parameter or assignment)

这些语句。(不能将其用作参数或赋值)

if (true) { getResult(); }

for (let i=0; i<10; i++) { console.log(i); }

This is an expression -> const res = getResult() or log(getResult())

这是一个表达式-> const = getResult()或log(getResult())

getResult();

Now, in Kotlin, the if-else statement returns a value, so it is an expression.

现在,在Kotlin中,if-else语句返回一个值,所以它是一个表达式。

const result = if (x > 10) true else false

More Examples

And here is where it starts to get ambiguous...

这里是它开始变得模糊的地方…

Block Statements vs Object Expressions

This can be both an expression that returns a javascript object, or a block statement that the last expression equal to the string Hero (with a tag called name)

这可以是返回一个javascript对象的表达式,也可以是最后一个表达式等于字符串Hero(带有一个名为name的标记)的块语句。

{
    name: "Hero"
}

The javascript eval statement will always eval a string as a statement, so putting the preceding code in eval

javascript eval语句将始终将一个字符串作为语句eval,因此将前面的代码放在eval中。

eval('{...}') 

will result in a String (the last expression of the block). Adding parenthesis around it

将会产生一个字符串(块的最后一个表达式)。添加括号围绕它

eval('({...})')

causes eval to parse it as an expression instead of a block statement, resulting in an object.

使eval将其解析为表达式而不是块语句,从而产生一个对象。

Javascript Functions

Functions can be both an expression and a statement (declaration)

函数可以是表达式,也可以是语句(声明)

Here is a function expression and function declaration. (You can assign it or use it as parameter, or it can be standalone)

这是一个函数表达式和函数声明。(可以将其分配或作为参数使用,也可以是独立的)

function () {
    console.log('ok');
}  

If you want to invoke it immediately, you need to turn it into a expression by using the surrounding parentheses.

如果要立即调用它,则需要使用周围的圆括号将其转换为表达式。

(function () {
    console.log('ok');
}())

If you do this, it will be a syntax error, because in the context, the function is a declaration statement, and you can only immediately invoke an expression.

如果您这样做,它将是一个语法错误,因为在上下文中,函数是一个声明语句,您只能立即调用一个表达式。

function () {
    console.log('ok');
}()

#1


171  

Expressions only contain identifiers, literals and 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:

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

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

#2


87  

Expression -- from my dictionary:

表达——从我的字典里:

expression: Mathematics a 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 Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.

在Python中,在Python语言引用中,表达式被广泛地覆盖,Python中的表达式由原子、主元素和操作符的语法合法组合构成。

Python expressions from Wikipedia

Python表达式从*

Examples of expressions:

表达式的例子:

Literals and syntactically correct combinations with Operators and built-in functions or 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

Statement from 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 Something and are often composed of expressions (or other statements)

总而言之:语句做了一些事情,通常由表达式(或其他语句)组成

The Python Language Reference covers Simple Statements and Compound Statements extensively.

Python语言引用广泛地包含简单的语句和复合语句。

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

然而,“陈述做某事”和“表达产生价值”的区别可以变得模糊起来:

  • List Comprehensions are considered "Expressions" but they have looping constructs and therfore also Do Something.
  • 列表的理解被认为是“表达式”,但是它们有循环结构,因此也会做一些事情。
  • The if is usually a statement, such as if x<0: x=0 but you can also have a conditional expression like x=0 if x<0 else 1 that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;
  • if通常是一个语句,比如x<0: x=0,但也可以有条件表达式,如x=0,如果x<0,则是表达式。在其他语言中,比如C,这种形式叫做算子x=x<0:1;
  • You can write you own Expressions by writing a function. def func(a): return a*a is an expression when used but made up of statements when defined.
  • 您可以通过编写函数来编写自己的表达式。def func(a): return a*a是使用时的表达式,但在定义时是由语句组成的。
  • An expression that returns None is a procedure in Python: def proc(): pass Syntactically, you can use proc() as an expression, but that is probably a bug...
  • 返回None的表达式是Python中的一个过程:def proc():通过语法,您可以使用proc()作为表达式,但这可能是一个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 form func(x=2) is illegal in Python (or at least it has a different meaning func(a=3) sets the named argument a to 3)
  • Python比C更严格一点,即表达式和语句之间的区别。在C中,任何表达式都是一种法律声明。你可以有func(x = 2);这是一个表达式还是一个语句?(回答:用作陈述的表达,带有副作用。)表单func(x=2)在Python中是非法的(或者至少它有一个不同的含义func(a=3)将命名的参数a设置为3)

#3


43  

Though this isn't related to Python:

虽然这与Python无关:

An expression evaluates to a value. A statement does something.

表达式求值。做一份声明。

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

#4


7  

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

语句表示一个动作或命令e。g打印语句,赋值语句。

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

#5


2  

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.

因为它不能被还原为一个值。

#6


1  

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:解释器总是打印出所有表达式的值。

#7


0  

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中可以做的任何事情:计算值、赋值、删除变量、打印值、从函数返回值、引发异常等等。

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())、运算符(例如,“2+3”)等,以产生一个值。

#8


0  

A statement contains a keyword.

语句包含一个关键字。

An expression does not contain a keyword.

表达式不包含关键字。

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

打印“hello”是语句,因为print是一个关键字。

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

“hello”是一个表达式,但是list压缩是针对这个的。

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

下面是一个表达式语句,没有列表理解是正确的:

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

#9


0  

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

}

}

#10


0  

Expressions:

表达式:

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

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

2.0 + 3是一个计算值为5.0的表达式,并且有一个与之相关联的类型浮动。

Statements

语句

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

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

#11


0  

  1. An expression is a statement that returns a value. So if it can appear on the right side of an assignment, or as a parameter to a method call, it is an expression.
  2. 表达式是返回值的语句。因此,如果它可以出现在赋值的右边,或者作为一个方法调用的参数,它就是一个表达式。
  3. Some code can be both an expression or a statement, depending on the context. The language may have a means to differentiate between the two when they are ambiguous.
  4. 根据上下文,一些代码可以是表达式或语句。这种语言可能有一种方法来区分两者之间的歧义。

Basic Examples

Here are some basic Javascript examples:

下面是一些基本的Javascript示例:

These are statements. (You can't use them as a parameter or assignment)

这些语句。(不能将其用作参数或赋值)

if (true) { getResult(); }

for (let i=0; i<10; i++) { console.log(i); }

This is an expression -> const res = getResult() or log(getResult())

这是一个表达式-> const = getResult()或log(getResult())

getResult();

Now, in Kotlin, the if-else statement returns a value, so it is an expression.

现在,在Kotlin中,if-else语句返回一个值,所以它是一个表达式。

const result = if (x > 10) true else false

More Examples

And here is where it starts to get ambiguous...

这里是它开始变得模糊的地方…

Block Statements vs Object Expressions

This can be both an expression that returns a javascript object, or a block statement that the last expression equal to the string Hero (with a tag called name)

这可以是返回一个javascript对象的表达式,也可以是最后一个表达式等于字符串Hero(带有一个名为name的标记)的块语句。

{
    name: "Hero"
}

The javascript eval statement will always eval a string as a statement, so putting the preceding code in eval

javascript eval语句将始终将一个字符串作为语句eval,因此将前面的代码放在eval中。

eval('{...}') 

will result in a String (the last expression of the block). Adding parenthesis around it

将会产生一个字符串(块的最后一个表达式)。添加括号围绕它

eval('({...})')

causes eval to parse it as an expression instead of a block statement, resulting in an object.

使eval将其解析为表达式而不是块语句,从而产生一个对象。

Javascript Functions

Functions can be both an expression and a statement (declaration)

函数可以是表达式,也可以是语句(声明)

Here is a function expression and function declaration. (You can assign it or use it as parameter, or it can be standalone)

这是一个函数表达式和函数声明。(可以将其分配或作为参数使用,也可以是独立的)

function () {
    console.log('ok');
}  

If you want to invoke it immediately, you need to turn it into a expression by using the surrounding parentheses.

如果要立即调用它,则需要使用周围的圆括号将其转换为表达式。

(function () {
    console.log('ok');
}())

If you do this, it will be a syntax error, because in the context, the function is a declaration statement, and you can only immediately invoke an expression.

如果您这样做,它将是一个语法错误,因为在上下文中,函数是一个声明语句,您只能立即调用一个表达式。

function () {
    console.log('ok');
}()