What is an expression in Python?

前端 未结 4 1342
醉话见心
醉话见心 2020-12-13 05:13

I have some confusion about its meaning or definition.

Isn\'t that some code that produce or calculate new data values? (Says Zelle in his book)

Then I wond

4条回答
  •  执念已碎
    2020-12-13 05:24

    TL;DR: Expressions are combinations of values and operators and always evaluate down to a single value. A statement is every other instruction. Some statements contain expressions.

    An expression is an instruction that combines values and operators and always evaluates down to a single value.

    For example, this is an expression:

    >>> 2 + 2
    

    The 2s are integer values and the + is the mathematical operator. This expression evaluates down to the single integer value 4.

    Technically, this is also an expression:

    >>> 4
    

    As an expression, it evaluates down to the single value 4.

    When I say values and operators, this isn't limited to math problems:

    >>> 'You will be ' + str(int(myAge) + 1) + ' next year.'
    

    The myAge variable evaluates to the value inside it. The function call int('5') evaluates to the function's return value, 5. All these string values are combined with the + operator (in this case, it's the string concatenation operator). No matter how big an expression is, it evaluates down to a single value: in this case, the string value 'You will be 6 next year.'

    Contrast this with a statement, which is a Python instruction that does not evaluate down to a value. A Python statement is pretty much everything else that isn't an expression. Here's an assignment statement:

    >>> spam = 2 + 2
    

    Here's an if statement:

    >>> if spam == 4:
    

    Here's a while statement for an infinite loop:

    >>> while True:
    

    Note that both of these statements contain expressions (even True, which evaluates down to the single value True). But not all statements use expressions in them. Here's a break statement:

    >>> break
    

提交回复
热议问题