Absolute Beginner's Python Programming by Unknown
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
The period in which a variable exists in memory is called its lifetime.
Variables defined inside a function exist only while the function executes. Once the function returns, the variables inside the function are destroyed.
Recursion
A recursive function is a function that can call itself. This enables the function to repeat itself several times.
Open the file recursion1.py. Here we have a recursive function that calculates the factorial of a number. Remember, to calculate the factorial you multiply all the numbers from 1 to the given number.
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
When we call the factorial function and pass a positive integer (n)
factorial(4)
It will recursively call itself by decreasing the number passed to the function (n) by one each time, then add the call to a call stack.