# Creating a multiline function with localized variables

I would like to create a function with several expressions in the code body.

For example, I would like to write something like this, but which will actually work.

myFunction[x]:=
y=x
y=y+3;
(y+3)^3


I know that I can do this :

myFunction[x]:=(y=x;y=y+3;(y+3)^3)


But it will be hardly writable if I have a lot of expression to evaluate.

How can I do it?

(I just installed Mathematica and read some tutorials on the internet so my knowledge is veeeeeery basic).

• Use Module[{y},...] to make y a local variable. You can use newlines, they have no syntactical meaning. Feb 28 '17 at 15:00
• You mean I should write : myFunction[x]:=Module[{y},y=x;y=y+3;(y+3)^3] And I can do newline between my ";" ? Feb 28 '17 at 15:04
• Take a look reference.wolfram.com/language/howto/… and mathematica.stackexchange.com/a/39464/5478 for more basic tutorials.
– Kuba
Feb 28 '17 at 15:04
• @Felix in cells they have, unless they are inside expressions.
– Kuba
Feb 28 '17 at 15:08
• Yes, within Module (or simply parentheses for that matter) you can use a newline for spacing, but you still need ; (CompoundExpression) or you end up multiplying expressions unintentionally. Please see (41091) for more. Feb 28 '17 at 15:11

You should write your function like so:

myFunction[x_] :=
Module[{y},
y = x;
y = y + 3;
(y + 3)^3]


Note the underscore in x_. This makes x into a formal argument that will not be confused with any definition of x you might have made.

Then, even when x and y have global values they will not interfere with either the proper definition of myFunction nor with calls to it.

x = 42; y = 43;
myFunction[1]


343

You can read more about defining functions here