Several people have mentioned already that you can use CompoundExpression
:
f[x_] := (y=x+5; y^2)
However, if you use the same variable x
in the expression as in the argument,
f[x_] := (x=x+5; x^2)
then you'll get errors when evaluating the function with a number. This is because :=
essentially defines a replacement of the pattern variables from the lhs, i.e. f[1]
evaluates to the (incorrect) (1 = 1+5; 1^2)
.
So, as Sjoerd said, use Module
(or Block
sometimes, but this one has caveats!) to localize a function-variable:
f[x_] := Module[{y}, y=x+5; y^2]
Finally, if you need a function that modified its arguments, then you can set the attribute HoldAll
:
Clear[addFive]
SetAttributes[addFive, HoldAll]
addFive[x_] := (x=x+5)
Then use it as
a = 3;
addFive[a]
a