difference between statements (statements) and expressions (expressions) in Python

Background

I see reading in my school homework, so when I read it, I run into the concepts of ʻexpressions and statements`. Even if I read it, the difference is not so clear, so I decided to investigate. ~~ I believe that the school side is not telling me to read this much and understand everything ... ~~

def. of statements and expressions

The definition by reading is

Statements typically describe actions. When the Python interpreter executes a statement, it carries out the corresponding action.

Does that mean x = 1 ory = "apple"? That was my interpretation, but stackoverflow

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. Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code.

This means that ʻexpressions can also be regarded as statements. While it can be completed with just ʻexpression, statement (which makes you think more when you read this area) The impression is that it works well with other blocks. There is almost certainly a ʻexpression in the statement`.

From quora

A statement is a complete line of code that performs some action, while an expression is any section of the code that evaluates to a value. Expressions can be combined “horizontally” into larger expressions using operators, while statements can only be combined “vertically” by writing one after another, or with block constructs. Every expression can be used as a statement (whose effect is to evaluate the expression and ignore the resulting value), but most statements cannot be used as expressions.

Also, the answer to ʻexpression` in this stackoverflow was easy to understand.

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.

Furthermore, here

A sentence is a linguistic element that completes on its own. An expression is basically a linguistic element that is not completed by itself and is used as part of a sentence or expression. Also, the biggest feature of the expression is that it returns a value (the statement does not return a value). For example, a constant expression returns the value itself. A conditional expression is an expression that returns a boolean value (True / False). There is a comparison expression as one of the conditional expressions, but since the conditional expression itself can be anything as long as it returns True / False, a simple Boolean True (constant expression) is also a conditional expression. A comparison expression can be a conditional expression because it compares the expressions on the left and right sides with a comparison operator in between and returns the result in True / False.

By the way, __ʻevaluate argumentsimply meanscalling function __. It happens when you actually pass the arguments in parentheses of the function. __ʻEvaluate function is different from calling function __. This was simply defined as having a function. So the correct order is ʻevaluate function → ʻevaluate argument function gets called.

Postscript

Even if I didn't bother to look for it, it was introduced in the next Lecture, so for the time being (laughs)

an expression describes a computation and evaluates to a value. all expressions can use function call notation

Each call expression called ʻadd (2, 3) is also a ʻexpression. ʻAdd is called ʻoperator, and what is in()is called ʻoperand. The call expression first recognizes ʻoperator and ʻoperand, treats ʻoperand as ʻargument, and uses functionto outputvalue. By the way, although it is self-evident, this can also be expressed as 2 + 3. Converting from ʻadd (2,3) to 2 + 3 is called __syntactic sugar __. Also, the signs +, *,-or / used in mathematics are called __infix notation __.

It is exactly the same as above, but it was also described in here, so it is partially reprinted.

Executing x = 2 does not return a value nor evaluate a function on some arguments, since the purpose of assignment is instead to bind a name to a value. In general, statements are not evaluated but executed; they do not produce a value but instead make some change. Each type of expression or statement has its own evaluation or execution procedure.

Addendum # 2

Reprinted from the "Statements" section of reading

Expressions can also be executed as statements, in which case they are evaluated, but their value is discarded. Executing a pure function has no effect, but executing a non-pure function can cause effects as a consequence of function application.

ref: Difference between pure function and non-pure function

def square(x):
    mul(x, x)# Watch out! This call doesn't return a value.

ʻExpression is processed in the same way as statement, but valueis not displayed. Therefore, we issuevalue together with ʻassignment, def, and return statements.

Addendum # 3

For reference, I personally made a simple diagram based on the professor's explanation of ʻexpression and statement` in a later lecture.

Screen Shot 2016-01-31 at 2.18.24 AM.png

Recommended Posts

difference between statements (statements) and expressions (expressions) in Python
Difference between list () and [] in Python
Difference between == and is in python
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
Difference between Ruby and Python in terms of variables
Difference between return, return None, and no return description in Python
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Python module num2words Difference in behavior between English and Russian
List concatenation method in python, difference between list.extend () and “+” operator
Overlapping regular expressions in Python and Java
Differences in authenticity between Python and JavaScript
Differences between Ruby and Python in scope
Differences in syntax between Python and Java
Difference between PHP and Python finally and exit
[Python] Difference between class method and static method
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
Differences in multithreading between Python and Jython
Difference in how to write if statement between ruby ​​and python
Transcendental simple and clear! !! Difference between single quotes and double quotes in Python
File open function in Python3 (difference between open and codecs.open and speed comparison)
Multiple regression expressions in Python
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Find the difference in Python
Difference between regression and classification
Use regular expressions in Python
[python] Calculation of months and years of difference in datetime
Wrap long expressions in python
Stack and Queue in Python
Mutual conversion between JSON and YAML / TOML in Python
About Python and regular expressions
Difference between np.array and np.arange
Difference between MicroPython and CPython
Unittest and CI in Python
Difference in writing method to read external source code between Ruby and Python
Compare "relationship between log and infinity" in Gauche (0.9.4) and Python (3.5.1)
Difference between ps a and ps -a
Difference between return and print-Python
[Python] Explain the difference between strftime and strptime in the datetime module with an example
Install OpenCV 3 (core + contrib) in Windows & Python 3 environment & Difference between OpenCV 2 and OpenCV 3 & Easy operation check
Python> Difference between inpbt and print (inpbt) output> [1. 2. 3.] / array ([1., 2., 3.], dtype = float32)
Useful tricks related to list and for statements in Python
Get the current date and time in Python, considering the time difference
Python tuple comprehensions and generator expressions
MIDI packages in Python midi and pretty_midi
Difference between SQLAlchemy filter () and filter_by ()
View photos in Python and html
Sorting algorithm and implementation in Python
Memorandum (difference between csv.reader and csv.dictreader)
Manipulate files and folders in Python