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

本文翻译自:What is the difference between an expression and a statement in Python?

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


#1楼

参考:https://stackoom.com/question/jPZf/Python中的表达式和语句有什么区别


#2楼

A statement contains a keyword. 语句包含关键字。

An expression does not contain a keyword. 表达式不包含关键字。

print "hello" is statement, because print is a keyword. print "hello"是语句,因为print是关键字。

"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))

#3楼

Statements represent an action or command eg 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

#4楼

I think an expression contains operators + operands and the object that holds the result of the operation... eg 我认为一个表达式包含运算符+操作数和持有该运算结果的对象...例如

var sum = a + b;

but a statement is simply a line of a code (it may be an expression) or block of code... eg 但是一条语句只是一行代码(可能是一个表达式)或代码块...例如

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

} }


#5楼

Expressions: 表达式:

  • Expressions are formed by combining objects and operators . 通过组合objectsoperators来形成表达式。
  • An expression has a value, which has a type. 表达式具有一个值,该值具有一个类型。
  • Syntax for a simple expression: 简单表达式的语法:

    2.0 + 3 is an expression which evaluates to 5.0 and has a type float associated with it. 2.0 + 3是一个表达式,计算结果为5.0并且具有与之关联的float类型。

    Statements 陈述

    Statements are composed of expression(s). 语句由表达式组成。 It can span multiple lines. 它可以跨越多行。


    #6楼

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

    你可能感兴趣的:(python,expression)