In Python, what is the difference between expressions and statements?
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:
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:
# all the above expressions
print 42
if x: do_y()
return
a = 7
Expression -- from the New Oxford American Dictionary:
expression: Mathematics a collection
of symbols that jointly express a
quantity : the expression for the
circumference of a circle is 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 expressions from Wikipedia
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
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.
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;
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.
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...
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 assignment statement of x=2 inside of the function call of func(x=2) in Python sets the named argument a to 2 only in the call to func and is more limited than the C example.
Though this isn't related to Python:
An expression evaluates to a value.
A statement does something.
>>> x + 2 # an expression
>>> x = 1 # a statement
>>> y = x + 1 # a statement
>>> print y # a statement (in 2.x)
2
An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not.
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.
Statements represent an action or command e.g 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
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.
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.
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.
STATEMENT:
A Statement is a action or a command that does something. Ex: If-Else,Loops..etc
val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")
EXPRESSION:
A Expression is a combination of values, operators and literals which yields something.
val a: Int = 5 + 5 #yields 10
Expressions always evaluate to a value, statements don't.
e.g.
variable declaration and assignment are statements because they do not return a value
const list = [1,2,3];
Here we have two operands - a variable 'sum' on the left and an expression on the right.
The whole thing is a statement, but the bit on the right is an expression as that piece of code returns a value.
const sum = list.reduce((a, b)=> a+ b, 0);
Function calls, arithmetic and boolean operations are good examples of expressions.
Expressions are often part of a statement.
The distinction between the two is often required to indicate whether we require a pice of code to return a value.
References
Expressions and statements
2.3 Expressions and statements - thinkpython2 by Allen B. Downey
2.10. Statements and Expressions - How to Think like a Computer Scientist by Paul Resnick and Brad Miller
An expression is a combination of values, variables, and operators. A value all by itself is
considered an expression, and so is a variable, so the following are all legal expressions:
>>> 42
42
>>> n
17
>>> n + 25
42
When you type an expression at the prompt, the interpreter evaluates it, which means that
it finds the value of the expression. In this example, n has the value 17 and n + 25 has the
value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a
value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a value to n. The second line is a print
statement that displays the value of n.
When you type a statement, the interpreter executes it, which means that it does whatever
the statement says. In general, statements don’t have values.
An expression translates to a value.
A statement consumes a value* to produce a result**.
*That includes an empty value, like: print() or pop().
**This result can be any action that changes something; e.g. changes the memory ( x = 1) or changes something on the screen ( print("x") ).
A few notes:
Since a statement can return a result, it can be part of an expression.
An expression can be part of another expression.
Statements before could change the state of our Python program: create or update variables, define function, etc.
And expressions just return some value can't change the global state or local state in a function.
But now we got :=, it's an alien!
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.
Statements
Statements are composed of expression(s). It can span multiple lines.
A statement contains a keyword.
An expression does not contain a keyword.
print "hello" is statement, because print is a keyword.
"hello" is an expression, but list compression is against this.
The following is an expression statement, and it is true without list comprehension:
(x*2 for x in range(10))
Python calls expressions "expression statements", so the question is perhaps not fully formed.
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#
An expression statement is limited to calling functions (e.g.,
math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.
I am new in prolog i have a code that i want to read from file then parse this is the code here
var x;
x <- (5 * 2);
return (x + 1).
now in prolog i want to tokenize this like this first
[’var’, ’x’, ’;’, ’x’,’<-’, ’(’, 5, ’*’, 2, ’)’, ’;’, ’return’, ’(’, ’x’, ’+’, 1, ’)’, ’.’]
the i want to implement predicate
parse(+TokenList, -AST)
then again
evaluate(+AST, -Number)
using SWIProlog
The parser should not allow the keywords of the language (e.g., the arithmetic operators, <-,
var, return) as variable identifiers
You can try tokenize_atom, to see if it fits your requirements.
Otherwise, bite the bullet and try to write your own DCG...
In my code I have a hash, each one with a set value of 0, after running through the code, I would like it to display "1", but it only displays a 0. Can anyone help, and please explain my error and why it didn't work.
puts "Hello!, and welcome to the 'Coin Calculator V1.0', please enter a value."
coin_value = gets.to_i
coin_num = {"quarters" => 0,"dimes" => 0,"nickels" => 0,"pennies" => 0}
if coin_value>25
coin_value-25
coin_num["quarters"]+1 // **basically, how do I add an integer value to the old integer?
puts coin_num["quarters"]
end
coin_num["quarters"] = coin_num["quarters"] + 1
which can be shortened using the += operator (addition assignment):
coin_num["quarters"] += 1
Neither of your arithmetic expressions changes anything.
coin_value - 25
That evaluates to 25 less than coin_value; if you printed it out or assigned it somewhere, you would see that. But since you don't do anything with the value, it just gets thrown away and nothing happens. Certainly, coin_value doesn't change.
Similarly,
coin_num["quarters"] + 1
evaluates to one more than the current value of coin_num["quarters"], but doesn't change anything.
If you want to change the value of a variable - any variable, whether a simple scalar like coin_value or an element of a Hash or Array - you have to use an assignment statement. You need an =, and the variable you want to change has to be on the left hand side of that =:
coin_value = coin_value - 25
coin_num['quarters'] = coin_num['quarters'] + 1
Ruby does define shorthand operators for modifying a variable using a simple expression involving that same variable's previous value:
coin_value -= 25
coin_num['quarters'] += 1
But you're still using = - it's just part of a compound assignment operator now.
I wanted to calculate the power sum S_p(x) = 1^p + 2^p + 3^p + ... + x^p using the code
powersum[x_,p_]:=sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum
but it seems to output 0 every time. Why does it do that?
As written, Mathematica is parsing your expression like this:
powersum[x_,p_]:=sum=0; (*Definition ended here*)
For[i=1,i<x,i++,sum=sum+i^p];
sum
You need to use to wrap your expression in parenthesis to make them all part of the function definition.
powersum[x_,p_]:=(sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum)
Often it is preferable to use Module[]:
powersum[x_,p_]:=Module[{sum},sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum]
or
powersum[x_,p_]:=Module[{sum=0},For[i=1,i<x,i++,sum=sum+i^p];sum]
this is essentially the same as wrapping in () except sum is protected in a local context.
of course for this example you could as well use :
powersum[x_,p_]:=Sum[i^p,{i,1,x-1}]
or
powersum[x_, p_] := Range[x - 1]^p // Total
Consider the following code snippet:
class Example
def my_attr=(value)
#_my_attr = value
#_my_attr * 3
end
end
I expect the expression Example.new.my_attr = 5 to return 15, but that turns out to be wrong. The original return value is always returned, even when I call the = method explicitly:
Example.new.my_attr = 5 # => 5
Example.new.my_attr=(5) # => 5
How and why does Ruby do this? Does Ruby treat methods that end in = specially, or is it some other mechanism? I guess this precludes chaining on return values of = methods, right? Is there a way to make Ruby behave differently, or is this just how it is?
Update: Credit to #jeffgran for this:
Example.new.send(:my_attr=, 5) # => 15
This is a workaround, but on another level even more perplexing, since that would mean send is clearly not always equivalent in behavior to calling a method directly.
This is how assignment works; the return value is ignored, and the result of an assignment expression is always the right-hand value. This is a fundamental feature of Ruby's grammar. left-hand side = right-hand side will always evaluate to right-hand side, regardless of whether left hand side is a variable (x), a method (object.x), a constant (X) or any expression.
Source: Programming Languages | Ruby
IPA Ruby Standardization WG Draft, 11.4.2.2.5, Single method assignments
Consider chaining of assignments, x = y = 3.
For this to work correctly, the result of y = 3 must be 3, regardless of the actual value returned by the y= method. x = y = 3 is meant to read as y = 3; x = 3, not as y = 3; x = y which is what would be implied if the return value from y= was treated as the result of y = 3.
Or consider all the other places assignment can be used. Sometimes, instead of this...
obj.x = getExpensiveThing()
if obj.x
...
... we write this ...
if obj.x = getExpensiveThing()
This couldn't work if the result of obj.x = ... could be any arbitrary thing, but we know it will work because the result of obj.x = y is always y.
Update
A comment on the question states:
Interesting, I wasn't aware of this scenario. It seems that method= returns whatever input is given...
No, it's an important distinction to make. This has nothing to do with the return value of method assignment, and it definitely does not "return whatever input is given", it returns whatever you tell it to return.
The whole point is that the return value is ignored by the grammar of the language; assignment doesn't evaluate to the return value of the attr= method, but the return value still exists as evidenced by the question itself: Example.new.send(:my_attr=, 5) # => 15. This works because it is not assignment. You're side-stepping that part of the Ruby language.
Update again
To be clear: x and y in my examples shouldn't be interpreted as literal Ruby variables, they are place holders for any valid left-hand side of an assignment. x or y could be any expression: a, obj.a, CONSTANT_A, Something::a, #instance_a, it's all the same. The value of assignment is always the right-hand side.