# Code for Factorial Function

Below I have my code that I created for finding the factorial of a number. The output I am getting when I enter MyFact[5] is Null Return[120]. I am rather new to Mathematica so I feel its a small semantic problem, but any help would be appreciated!

MyFact[n_] :=
Module [
{
OneAgoFact,
MyNewFact,
Counter
},
MyNewFact = 1;
OneAgoFact = 1;
If[ n > 0,
Counter = 1;
While[Counter <= n,
MyNewFact = OneAgoFact*Counter;
OneAgoFact = MyNewFact;
Counter = Counter + 1;
]
]
Return[MyNewFact]
]

• You forgot to put a semicolon at the end of your If[]. If you do that, you can remove the Return[]. – J. M.'s torpor Sep 6 '17 at 2:13

Turning J.M.'s comment into an answer, you need to follow the If[...] statement with a semicolon. Otherwise If evaluates to what While evaluates to, which is Null, and without the semicolon Mathematica interprets If[...] Return[...] as multiplication.

ClearAll[MyFact]
MyFact[n_] := Module[{OneAgoFact, MyNewFact, Counter}, MyNewFact = 1;
OneAgoFact = 1;
If[n > 0, Counter = 1;
While[Counter <= n, MyNewFact = OneAgoFact*Counter;
OneAgoFact = MyNewFact;
Counter = Counter + 1;]];
MyNewFact]


Notice that you can replace Return[MyNewFact] simply with MyNewFact, as Module returns the evaluated form of its second argument.

One last note: you might want to avoid capital letters at the start of variable names, as they often conflict with built-in symbols. Symbols (i.e., variables or functions) which start with lowercase letters will never conflict with built-ins. Of course this is up to you.