What is an expression in Python?

前端 未结 4 1344
醉话见心
醉话见心 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

    Expressions represent something, like a number, a string, or an instance of a class. Any value is an expression!

    Anything that does something is a statement. Any assignment to a variable or function call is a statement. Any value contained in that statement in an expression.

    foo = "hello" is a statement that assigns foo to the value of the expression "hello". Since the code "hello" is a simple expression, meaning it contains no operations, nothing is actually evaluated, so foo is just assigned to "hello". More complex expressions actually evaluate things, like adding numbers. Using the word expression seems like it is making things more confusing. Expressions are nothing but values, except they can have operations like addition or subtraction.

    eval evaluates the string as if it were a python expression. Eval does takes an expression as an argument. However, there's nothing special about this since every single value is an expression. Saying "eval takes a value as an argument" is saying exactly the same thing, but it sounds much simpler. :D

    eval( "2+2" ) passes the string "2+2" to the function. The function evaluates the expression contained in the string, which comes out to 4.

    The book by Zelle says eval() evaluates string as an expression, what does that exactly mean if string is already an expression?

    Any string is an expression since it represents a value. However, what is in the string has absolutely no impact on it being an expression. If its a value, its an expression. When it is "evaluated as an expression by eval", the characters inside the string are executed as if they were a python expression.

提交回复
热议问题