Funny enough, all of the code is running! It just isn't showing anything, because the print
statement isn't being called! Lets decompose the user function and see what it does.
What the code is doing
n = int(raw_input("What number would you like to use?"))
Convert the string the user types into an integer and store it into the variable (or, if you want to be pythonic-ly correct, the name) n
.
try:
factorial(int(n))
Try to convert n
into an integer (again) and send said integer to the factorial
function. Note that n
here is already an integer! So this will always succeed. Just call the function, nothing more.
except ValueError:
print "You must choose a number. Please try again."
return user()
If ValueError
is raised, print an error message, then return the value of user
.
We don't print anything whether the conversion was successful or not. We just run a single function then exit. What function do we run?
def factorial(n):
while n > 0:
return n * factorial(n-1)
return 1
print factorial(n)
Note that in this function the code says to print a value after returning a value. Once a function returns, nothing after the return statement is run. The print
statement will not be executed! So this function correctly computes the factorial (recursively), and returns it. Nothing else!
This is why your program will seem to do nothing. This function is called, computes, and returns the answer. The returned answer is simply ignored!
What does this mean?
There are three key lines in your code that define why it's doing what it's doing.
- You convert the input from the user into an integer and store it in
n
- This will raise
ValueError
if the user types anything that isn't an integer.
- Note that this still happens! if you run the code, type
b
, then press enter, an exception (ValueError
) will be raised.
- You convert
n
into an integer and pass it to factorial
.
- Although this is in the
try
block (as it should be), n
is already an integer. This is why your exception code will never run.
- Your only print statement (after getting valid input from the user) is inside the
factorial
function, after the return statement. It will never be executed. This is why nothing is printed.
- I don't recommend printing the result inside of a recursive function. It can be done, but it is generally better to return the result and print the returned value, outside of the recursive function. (perhaps in the user function, instead of calling
factorial(n)
printing what it returns would be better!)
I hope that this helped to clarify exactly what is going on with the code, and I hope I was able to answer your question! Happy coding! :D